http_addr = ":8081"
grpc_addr = ":8082"
package main
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
app "github.com/webws/go-moda"
"github.com/webws/go-moda/config"
pbexample "github.com/webws/go-moda/example/pb/example"
"github.com/webws/go-moda/logger"
modagrpc "github.com/webws/go-moda/transport/grpc"
modahttp "github.com/webws/go-moda/transport/http"
)
var ServerName string
type Config struct {
HttpAddr string `json:"http_addr" toml:"http_addr"`
GrpcAddr string `json:"grpc_addr" toml:"grpc_addr"`
}
func main() {
conf := &Config{}
if err := config.NewConfigWithFile("./conf.toml").Load(conf); err != nil {
logger.Fatalw("NewConfigWithFile fail", "err", err)
}
// http server
gin, httpSrv := modahttp.NewGinHttpServer(
modahttp.WithAddress(conf.HttpAddr),
)
registerHttp(gin)
// grpc server
grpcSrv := modagrpc.NewServer(
modagrpc.WithServerAddress(conf.GrpcAddr),
)
grecExample := &ExampleServer{}
pbexample.RegisterExampleServiceServer(grpcSrv, grecExample)
// app run
a := app.New(
app.Server(httpSrv, grpcSrv),
app.Name(ServerName),
)
if err := a.Run(); err != nil {
logger.Fatalw("app run error", "err", err)
}
}
func registerHttp(g *gin.Engine) {
g.GET("/helloworld", func(c *gin.Context) {
logger.Debugw("Hello World")
c.JSON(http.StatusOK, http.StatusText(http.StatusOK))
})
}
type ExampleServer struct {
pbexample.UnimplementedExampleServiceServer
}
func (s *ExampleServer) SayHello(ctx context.Context, req *pbexample.HelloRequest) (*pbexample.HelloResponse, error) {
return &pbexample.HelloResponse{Message: "Hello " + req.Name}, nil
}
go run ./ -c ./conf.toml
其他服务启用示例
启动服务默认开启 pprof 性能分析,浏览器打开 http://localhost:8081/debug/ 查看
可视化分析 gouroutine
go tool pprof http://localhost:8081/debug/pprof/goroutine
(pprof) web
可能提示 需要先安装 graphviz, mac 下可以使用 brew 安装
brew install graphviz
import "github.com/webws/go-moda/tracing"
func main(){
//...
shutdown, err := tracing.InitJaegerProvider(conf.JaegerUrl, "grpc-server")
if err != nil {
panic(err)
}
defer shutdown(context.Background())
//...
}
ctx, span := tracing.Start(c.Request().Context(), "api1")
defer span.End()
//...
gin, httpSrv := modahttp.NewGinHttpServer(
modahttp.WithAddress(conf.HttpAddr),
modahttp.WithTracing(true),
)
// ...
_, err := modahttp.CallAPI(ctx, url, "POST", nil)