Vasiliy Tolstov 9f2dd3ed35 allow to generate standalone code
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-02-25 14:44:50 +03:00

82 lines
2.6 KiB
Go

package main
import (
"google.golang.org/protobuf/compiler/protogen"
)
var (
chiPackageFiles map[protogen.GoPackageName]struct{}
)
func (g *Generator) chiGenerate(component string, plugin *protogen.Plugin) error {
chiPackageFiles = make(map[protogen.GoPackageName]struct{})
for _, file := range plugin.Files {
if !file.Generate {
continue
}
if len(file.Services) == 0 {
continue
}
if _, ok := chiPackageFiles[file.GoPackageName]; ok {
continue
}
chiPackageFiles[file.GoPackageName] = struct{}{}
gname := "micro" + "_" + component + ".pb.go"
path := file.GoImportPath
if g.standalone {
path = "."
}
gfile := plugin.NewGeneratedFile(gname, path)
gfile.P("// Code generated by protoc-gen-micro")
gfile.P("package ", file.GoPackageName)
gfile.P()
gfile.Import(contextPackage)
gfile.Import(fmtPackage)
gfile.Import(httpPackage)
gfile.Import(reflectPackage)
gfile.Import(stringsPackage)
gfile.Import(chiPackage)
gfile.Import(chiMiddlewarePackage)
gfile.Import(microApiPackage)
gfile.P("type routeKey struct{}")
gfile.P("func RouteName(ctx ", contextPackage.Ident("Context"), ") (string, bool) {")
gfile.P("value, ok := ctx.Value(routeKey{}).(string)")
gfile.P("return value, ok")
gfile.P("}")
gfile.P()
gfile.P("func RegisterHandlers(r *", chiPackage.Ident("Mux"), ", h interface{}, eps []*", microApiPackage.Ident("Endpoint"), ") error {")
gfile.P("v := ", reflectPackage.Ident("ValueOf"), "(h)")
gfile.P("if v.NumMethod() < 1 {")
gfile.P(`return `, fmtPackage.Ident("Errorf"), `("handler has no methods: %T", h)`)
gfile.P("}")
gfile.P("for _, ep := range eps {")
gfile.P(`idx := `, stringsPackage.Ident("Index"), `(ep.Name, ".")`)
gfile.P("if idx < 1 || len(ep.Name) <= idx {")
gfile.P(`return `, fmtPackage.Ident("Errorf"), `("invalid `, microApiPackage.Ident("Endpoint"), ` name: %s", ep.Name)`)
gfile.P("}")
gfile.P("name := ep.Name[idx+1:]")
gfile.P("m := v.MethodByName(name)")
gfile.P("if !m.IsValid() || m.IsZero() {")
gfile.P(`return `, fmtPackage.Ident("Errorf"), `("invalid handler, method %s not found", name)`)
gfile.P("}")
gfile.P("rh, ok := m.Interface().(func(", httpPackage.Ident("ResponseWriter"), ", *", httpPackage.Ident("Request"), "))")
gfile.P("if !ok {")
gfile.P(`return `, fmtPackage.Ident("Errorf"), `("invalid handler: %#+v", m.Interface())`)
gfile.P("}")
gfile.P("for _, method := range ep.Method {")
gfile.P("r.With(", chiMiddlewarePackage.Ident("WithValue"), "(routeKey{}, ep.Name)).MethodFunc(method, ep.Path[0], rh)")
gfile.P("}")
gfile.P("}")
gfile.P("return nil")
gfile.P("}")
}
return nil
}