【问题标题】:Unmarshalling JSON content from a a file using GO and generate .go files using the GO template package使用 GO 从文件中解组 JSON 内容并使用 GO 模板包生成 .go 文件
【发布时间】:2015-01-20 07:32:56
【问题描述】:

我有兴趣阅读模式(json 格式的文本文件)并将其解组为模式(为此我在 .GO 文件中定义了一些 JSON 结构)并且对于模式中的每种类型的结构,我想生成一个相应的 .go 文件,其中包含使用模板包 (http://golang.org/pkg/text/template/) 执行 CRUD 操作以生成这些文件的代码。

架构文件中的结构示例 - {

type struct XYZ {
    Type         string                 `json:"type,omitempty"`
    ResourceType string                 `json:"resourceType,omitempty"`
    Links        map[string]string      `json:"links,omitempty"`

}

The text file has a JSON structured data which is something of this form -

{
        "type": "collection",
        "resourceType": "schema",
        "links": {
        "self": "…/v1/schemas",
        },
        "createTypes": { },
        "actions": { },
        "data": [ 86 items
        {
        "id": "schema",
        "type": "schema",
        "links": {
        "self": "/schemas/schema",
        "collection": "…/schemas",
        },
         ...

     }

}

有人可以帮我,我怎么可能使用 GO 模板包为不同的结构生成这些 CRUD 操作的代码。

【问题讨论】:

    标签: json go go-templates


    【解决方案1】:

    您可能会发现go generate 很有用。


    proposal: go generate

    为 Go 提议的新 go tool 子命令 1.4.请参阅此线程中的设计文档和评论。

    http://golang.org/s/go1.4-generate

    -抢劫


    Go generate: A Proposal

    简介

    go build 命令可以自动构建 Go 程序,但是 有时需要进行初步处理,进行构建的处理 不支持。激励的例子包括:

    • yacc:从 yacc 语法 (.y) 文件生成 .go 文件
    • protobufs:从协议缓冲区定义 (.proto) 文件生成 .pb.go 文件
    • Unicode:从 UnicodeData.txt 生成表
    • HTML:将 .html 文件嵌入到 Go 源代码中
    • bindata:在 Go 源码中将二进制文件(如 JPEG)转换为字节数组

    还有其他可以想象的处理步骤:

    • 字符串方法:为用作枚举常量的类型生成 String() 字符串方法
    • 宏:在给定通用包的情况下生成自定义实现,例如 sort.Ints from ints

    该提案提供了一种设计,可实现此类平滑自动化 处理。

    【讨论】:

    • 我曾经在 GO 中使用模板包来生成代码。我必须先自己编写一个模板,然后使用 {{ 之类的模板语法将需要通用的内容替换为结构字段架构.ID }}。当程序像这样运行并使用 os.Create(schema.ID + ".go") 时,它将生成具有模式名称的 .GO 文件。
    猜你喜欢
    • 1970-01-01
    • 2015-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-11
    相关资源
    最近更新 更多