您的位置 首页 golang

gencodec工具


gencodec

百度了一下,居然找不到gencodec工具的中文使用介绍,对我这种拿来主义的人真有点不适应,简单总结一下介绍使用。

gencodec是一个非常便捷的通过类型自动生成marshaling代码的工具,工具的安装就不细说了,基本没有使用其他库除了golang.org/x里某些库,地址:https://github.com/fjl/gencodec

使用方式:

gencodec -type MyType -field-override MyTypeMarshaling -formats json,yaml,toml -out mytype_json.go

在相应的包下指定:

  • type: 需要生成的类型名
  • formats: 样式,支持三种json,yaml,toml,默认json
  • field-override: (可选)覆盖类型
  • out: 生成的文件

类型

type foo struct {    Required string `gencodec:"required"`    //unmarshaling时需要检查该字段是否存在    Optional string                         // 文件中字段以原名标识    Renamed  string `json:"otherName"`      //封送到相应样式文件中的字段名 }

字段覆盖

type foo struct {    Field        string    SpecialField string}func (f foo) Func() string {    return f.Field + "-" + f.SpecialField}type fooMarshaling struct {    SpecialField specialString // overrides type of SpecialField when marshaling/unmarshaling    Func string `json:"id"`    // adds the result of foo.Func() to the serialised object under the key id}

gencodec的调用可以指定一个额外的“字段覆盖”结构,从中进行封送处理类型替换。如果覆盖结构体中字段名称与原结构体中字段匹配,则生成的封送处理方法将使用覆盖的类型并与原始字段类型进行转换。如果覆盖结构体中字段名称与原结构体中字段不匹配,但有与原结构体中的同名且无参数的方法,并且该方法的返回值与字段类型相同,则Marshal*调用该方法。如果有匹配的方法F,但是返回类型或参数不合适,就会引发错误;unmarshaling时该字段无意义。

type specialString stringfunc (s *specialString) UnmarshalJSON(input []byte) error { ... }type Foo struct{ S string }type fooMarshaling struct{ S specialString }// 被自动转换为func (f *Foo) UnmarshalJSON(input []byte) error {    var dec struct{ S *specialString }    ...    f.S = string(dec.specialString)   // 直接类型转换    ...}

覆盖结构体中的字段类型必须可以简单地转换为原始字段类型。gencodec支持以下转换:

  • 如果字段是可直接分配的,则不会发出转换。
  • 如果字段可以根据Go语言规则进行转换,则会发出一个简单的转换。
    如上,覆盖结构体fooMarshaling.S的类型specialString可直接转成string,即使specialString实现了UnmarshalJSON,也不会在gencodec的unmarshaling中嵌套调用,而是直接转换。

参考:

https://godoc.org/github.com/fjl/gencodec


文章来源:智云一二三科技

文章标题:gencodec工具

文章地址:https://www.zhihuclub.com/4888.shtml

关于作者: 智云科技

热门文章

网站地图