I'm trying to use the ast and parse packages to find the fields in two 
separate structs one that will be called Inputs and the other Outputs. 
these can change but as an example i'm trying to parse these

package main

import (
       "fmt"
)

type Inputs struct {
       Name string `json:"name"`
       Age  int    `json:"age"`
}

type Outputs struct {
       Number float `json:"number"`
}

func main() {

        fmt.Println("Hello World!")
}



I have the following which can pick out the two structs but i'm now lost on 
how to loop through the fields to get name, type and commenty bit 
`json:"name"` at the end. 

package main

import (
        "fmt"
        "go/ast"
        "go/parser"
        "go/token"
        "log"
)

func main() {

        fset := token.NewFileSet()
        file, err := parser.ParseFile(fset, "sample/main.go", nil, 0)
        if err != nil {
                log.Fatal(err)
        }
        ast.Walk(VisitorFunc(FindTypes), file)

}

type VisitorFunc func(n ast.Node) ast.Visitor

func (f VisitorFunc) Visit(n ast.Node) ast.Visitor {
        return f(n)
}

func FindTypes(n ast.Node) ast.Visitor {
        switch n := n.(type) {
        case *ast.Package:
                return VisitorFunc(FindTypes)
        case *ast.File:
                return VisitorFunc(FindTypes)
        case *ast.GenDecl:
                if n.Tok == token.TYPE {
                        return VisitorFunc(FindTypes)
                }
        case *ast.TypeSpec:
                if n.Name.Name == "Inputs" {
                        //We have hit the inputs struct
                        fmt.Println(n.Name.Name)
                }
                if n.Name.Name == "Outputs" {
                        //We have hit the outputs struct
                        fmt.Println(n.Name.Name)
                }
        }
        return nil
}

Any suggestions as to how to do it?

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to