Skip to content

Instantly share code, notes, and snippets.

@podhmo podhmo/main.go
Created Jan 31, 2018

Embed
What would you like to do?
package main
import (
"fmt"
"go/ast"
"go/importer"
"go/parser"
"go/token"
"go/types"
"log"
"reflect"
)
func main() {
fset := token.NewFileSet()
code := (`
package p
type S struct {
Name string ` + "`" + `json:"name"` + "`" + `
Age int ` + "`" + `json:"age"` + "`" + `
i int
}
`)
conf := types.Config{
Importer: importer.Default(),
Error: func(err error) {
fmt.Printf("!!! %#v\n", err)
},
}
file, err := parser.ParseFile(fset, "p", code, parser.AllErrors)
if err != nil {
log.Fatal(err)
}
pkg, err := conf.Check("p", fset, []*ast.File{file}, nil)
if err != nil {
log.Fatal(err)
}
S := pkg.Scope().Lookup("S")
internal := S.Type().Underlying().(*types.Struct)
for i := 0; i < internal.NumFields(); i++ {
jsonname, found := reflect.StructTag(internal.Tag(i)).Lookup("json")
field := internal.Field(i)
fmt.Printf("%v (exported=%t, jsonname=%s, found=%t)\n", field, field.Exported(), jsonname, found)
}
}
field Name string (exported=true, jsonname=name, found=true)
field Age int (exported=true, jsonname=age, found=true)
field i int (exported=false, jsonname=, found=false)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.