gpt4 book ai didi

json - 使用 GO 从文件中解码 JSON 内容并使用 GO 模板包生成 .go 文件

转载 作者:IT王子 更新时间:2023-10-29 01:43:00 25 4
gpt4 key购买 nike

我有兴趣阅读模式(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 操作的代码。

最佳答案

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


proposal: go generate

New go tool subcommand proposed for Go 1.4. Please see the design document and comment in this thread.

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

-rob


Go generate: A Proposal

Introduction

The go build command automates the construction of Go programs but sometimes preliminary processing is required, processing that go build does not support. Motivating examples include:

  • yacc: generating .go files from yacc grammar (.y) files
  • protobufs: generating .pb.go files from protocol buffer definition (.proto) files
  • Unicode: generating tables from UnicodeData.txt
  • HTML: embedding .html files into Go source code
  • bindata: translating binary files such as JPEGs into byte arrays in Go source

There are other processing steps one can imagine:

  • string methods: generating String() string methods for types used as enumerated constants
  • macros: generating customized implementations given generalized packages, such as sort.Ints from ints

This proposal offers a design for smooth automation of such processing.

关于json - 使用 GO 从文件中解码 JSON 内容并使用 GO 模板包生成 .go 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27073484/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com