8

gencodec工具

 4 years ago
source link: https://studygolang.com/articles/29133
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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 string

func (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

欢迎关注我们的微信公众号,每天学习Go知识

FveQFjN.jpg!web

Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK