Skip to content

Commit

Permalink
add http2grpc flag to support expose RESTful endpoints to grpc service
Browse files Browse the repository at this point in the history
  • Loading branch information
wubin1989 committed Nov 18, 2023
1 parent 96d9d13 commit 48c2a75
Show file tree
Hide file tree
Showing 12 changed files with 481 additions and 23 deletions.
9 changes: 8 additions & 1 deletion cmd/grpc.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
)

var naming string
var http2grpc bool

var grpcCmd = &cobra.Command{
Use: "grpc",
Expand All @@ -20,12 +21,18 @@ var grpcCmd = &cobra.Command{
case "snake":
fn = strcase.ToSnake
}
s := svc.NewSvc("", svc.WithProtoGenerator(v3.NewProtoGenerator(v3.WithFieldNamingFunc(fn))))
s := svc.NewSvc("",
svc.WithProtoGenerator(v3.NewProtoGenerator(v3.WithFieldNamingFunc(fn))),
svc.WithHttp2Grpc(http2grpc),
svc.WithAllowGetWithReqBody(allowGetWithReqBody),
)
s.Grpc()
},
}

func init() {
svcCmd.AddCommand(grpcCmd)
grpcCmd.Flags().StringVar(&naming, "case", "lowerCamel", `protobuf message field naming strategy, only support "lowerCamel" and "snake"`)
grpcCmd.Flags().BoolVar(&http2grpc, "http2grpc", false, `whether need RESTful api for your grpc service`)
grpcCmd.Flags().BoolVar(&allowGetWithReqBody, "allowGetWithReqBody", false, "Whether allow get http request with request body.")
}
6 changes: 3 additions & 3 deletions cmd/internal/svc/codegen/grpcannotation.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ func GenMethodAnnotationStore(dir string, ic astutils.InterfaceCollector) {
sqlBuf bytes.Buffer
fi os.FileInfo
)
grpcDir = filepath.Join(dir, "transport/grpc")
grpcDir = filepath.Join(dir, "transport", "grpc")
if err = os.MkdirAll(grpcDir, os.ModePerm); err != nil {
panic(err)
}
Expand All @@ -65,14 +65,14 @@ func GenMethodAnnotationStore(dir string, ic astutils.InterfaceCollector) {
panic(err)
}
if fi != nil {
logrus.Warningln("file handler.go will be overwritten")
logrus.Warningln("file annotation.go will be overwritten")
}
if f, err = os.Create(annotationFile); err != nil {
panic(err)
}
defer f.Close()

if tpl, err = template.New("annotation.go.tmpl").Parse(annotationTmpl); err != nil {
if tpl, err = template.New(annotationTmpl).Parse(annotationTmpl); err != nil {
panic(err)
}
if err = tpl.Execute(&sqlBuf, struct {
Expand Down
126 changes: 126 additions & 0 deletions cmd/internal/svc/codegen/grpchttpmain.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
package codegen

import (
"bytes"
"github.com/unionj-cloud/go-doudou/v2/cmd/internal/templates"
"github.com/unionj-cloud/go-doudou/v2/toolkit/astutils"
v3 "github.com/unionj-cloud/go-doudou/v2/toolkit/protobuf/v3"
"github.com/unionj-cloud/go-doudou/v2/version"
"os"
"path/filepath"
"strings"
"text/template"
)

var mainTmplGrpcHttp = templates.EditableHeaderTmpl + `package main
import (
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
grpczerolog "github.com/grpc-ecosystem/go-grpc-middleware/providers/zerolog/v2"
grpc_recovery "github.com/grpc-ecosystem/go-grpc-middleware/recovery"
grpc_ctxtags "github.com/grpc-ecosystem/go-grpc-middleware/tags"
grpc_opentracing "github.com/grpc-ecosystem/go-grpc-middleware/tracing/opentracing"
"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/logging"
"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/tags"
grpc_prometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
"github.com/unionj-cloud/go-doudou/v2/toolkit/zlogger"
"google.golang.org/grpc"
"github.com/unionj-cloud/go-doudou/v2/framework/grpcx"
{{.ServiceAlias}} "{{.ServicePackage}}"
"{{.ConfigPackage}}"
pb "{{.PbPackage}}"
"{{.HttpPackage}}"
"github.com/unionj-cloud/go-doudou/v2/framework/rest"
)
func main() {
conf := config.LoadFromEnv()
svc := {{.ServiceAlias}}.New{{.SvcName}}(conf)
go func() {
grpcServer := grpcx.NewGrpcServer(
grpc.StreamInterceptor(grpc_middleware.ChainStreamServer(
grpc_ctxtags.StreamServerInterceptor(),
grpc_opentracing.StreamServerInterceptor(),
grpc_prometheus.StreamServerInterceptor,
tags.StreamServerInterceptor(tags.WithFieldExtractor(tags.CodeGenRequestFieldExtractor)),
logging.StreamServerInterceptor(grpczerolog.InterceptorLogger(zlogger.Logger)),
grpc_recovery.StreamServerInterceptor(),
)),
grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(
grpc_ctxtags.UnaryServerInterceptor(),
grpc_opentracing.UnaryServerInterceptor(),
grpc_prometheus.UnaryServerInterceptor,
tags.UnaryServerInterceptor(tags.WithFieldExtractor(tags.CodeGenRequestFieldExtractor)),
logging.UnaryServerInterceptor(grpczerolog.InterceptorLogger(zlogger.Logger)),
grpc_recovery.UnaryServerInterceptor(),
)),
)
pb.Register{{.GrpcSvcName}}Server(grpcServer, svc)
grpcServer.Run()
}()
handler := httpsrv.New{{.SvcName}}Http2Grpc(svc)
srv := rest.NewRestServer()
srv.AddRoute(httpsrv.Routes(handler)...)
srv.Run()
}
`

// GenMainGrpcHttp generates main function for grpc service
func GenMainGrpcHttp(dir string, ic astutils.InterfaceCollector, grpcSvc v3.Service) {
var (
err error
mainfile string
f *os.File
tpl *template.Template
cmdDir string
svcName string
alias string
source string
)
cmdDir = filepath.Join(dir, "cmd")
if err = MkdirAll(cmdDir, os.ModePerm); err != nil {
panic(err)
}
svcName = ic.Interfaces[0].Name
alias = ic.Package.Name
mainfile = filepath.Join(cmdDir, "main.go")
servicePkg := astutils.GetPkgPath(dir)
cfgPkg := astutils.GetPkgPath(filepath.Join(dir, "config"))
pbPkg := astutils.GetPkgPath(filepath.Join(dir, "transport", "grpc"))
httpsrvPkg := astutils.GetPkgPath(filepath.Join(dir, "transport", "httpsrv"))
if _, err = Stat(mainfile); os.IsNotExist(err) {
if f, err = Create(mainfile); err != nil {
panic(err)
}
defer f.Close()
if tpl, err = template.New(mainTmplGrpcHttp).Parse(mainTmplGrpcHttp); err != nil {
panic(err)
}
var buf bytes.Buffer
if err = tpl.Execute(&buf, struct {
ServicePackage string
ConfigPackage string
PbPackage string
SvcName string
ServiceAlias string
Version string
GrpcSvcName string
HttpPackage string
}{
ServicePackage: servicePkg,
ConfigPackage: cfgPkg,
PbPackage: pbPkg,
SvcName: svcName,
ServiceAlias: alias,
Version: version.Release,
GrpcSvcName: grpcSvc.Name,
HttpPackage: httpsrvPkg,
}); err != nil {
panic(err)
}
source = strings.TrimSpace(buf.String())
astutils.FixImport([]byte(source), mainfile)
}
}
2 changes: 1 addition & 1 deletion cmd/internal/svc/codegen/grpcproto.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ func GenGrpcProto(dir string, ic astutils.InterfaceCollector, p protov3.ProtoGen
f *os.File
grpcDir string
)
grpcDir = filepath.Join(dir, "transport/grpc")
grpcDir = filepath.Join(dir, "transport", "grpc")
if err = os.MkdirAll(grpcDir, os.ModePerm); err != nil {
panic(err)
}
Expand Down
Loading

0 comments on commit 48c2a75

Please sign in to comment.