github.com/songzhibin97/gkit@v1.2.13/parser/parse_go/parse_go.go (about) 1 package parse_go 2 3 import ( 4 "fmt" 5 "go/ast" 6 "go/parser" 7 "go/token" 8 "io/ioutil" 9 "strings" 10 11 "github.com/songzhibin97/gkit/options" 12 gparser "github.com/songzhibin97/gkit/parser" 13 ) 14 15 func ParseGo(filepath string, options ...options.Option) (gparser.Parser, error) { 16 data, err := ioutil.ReadFile(filepath) 17 if err != nil { 18 return nil, err 19 } 20 fSet := token.NewFileSet() 21 // fParse: 解析到的内容 22 fParse, err := parser.ParseFile(fSet, filepath, data, parser.ParseComments) 23 if err != nil { 24 return nil, err 25 } 26 // 将注释存档 27 var comment []*Note 28 for _, group := range fParse.Comments { 29 for _, c := range group.List { 30 comment = append(comment, &Note{Comment: c}) 31 } 32 } 33 // 根据内容找到 struct 以及 func 34 ret := CreateGoParsePB(fParse.Name.Name, filepath, comment) 35 for _, v := range options { 36 v(ret) 37 } 38 for _, decl := range fParse.Decls { 39 switch v := decl.(type) { 40 case *ast.GenDecl: 41 ret.parseStruct(v) 42 case *ast.FuncDecl: 43 ret.parseFunc(v) 44 } 45 } 46 return ret, ret.checkFormat() 47 } 48 49 func parseTag(file *File) { 50 tags := strings.Split(file.Tag, " ") 51 for _, tag := range tags { 52 if strings.Contains(tag, "gkit:") { 53 num := strings.Split(strings.Replace(tag, "gkit:", "", -1), ",") 54 for _, flag := range num { 55 if strings.Contains(flag, "pType=") { 56 t := []byte(strings.Replace(flag, "pType=", "", -1)) 57 r := make([]byte, 0, 10) 58 for _, v := range t { 59 if v == '"' || v == '`' || v == ';' { 60 continue 61 } 62 r = append(r, v) 63 } 64 file.TypePB = string(r) 65 } 66 } 67 } 68 } 69 } 70 71 func parseDoc(server *Server) { 72 defer func() { 73 if err := recover(); err != nil { 74 fmt.Println("panic:", err) 75 return 76 } 77 }() 78 for _, doc := range server.Doc { 79 if strings.Contains(doc, "@method") { 80 server.Method = strings.Split(doc, ":")[1] 81 } 82 if strings.Contains(doc, "@service") { 83 server.ServerName = strings.Split(doc, ":")[1] 84 } 85 if strings.Contains(doc, "@router") { 86 server.Router = strings.Split(doc, ":")[1] 87 } 88 } 89 }