123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- package main
- import (
- "../clientImpl"
- "../example"
- "../serverImpl"
- "fmt"
- "git.wanpinghui.com/WPH/go_common/wph"
- "git.wanpinghui.com/WPH/go_common/wph/logger"
- "github.com/gin-gonic/gin"
- "github.com/sirupsen/logrus"
- "google.golang.org/grpc"
- "net/http"
- )
- // HTTP边界服务,同时也是后端服务的客户端
- // Istio对比测试用,部署于无Istio的环境
- var logB *logger.Logger
- func main() {
- logB = logger.New()
- logB.Level = logrus.WarnLevel
- router := gin.New()
- // 添加 GIN 请求处理中间件
- //router.Use(
- // gzip.Gzip(gzip.DefaultCompression),
- // mw.Favicon("./static/favicon.ico"), // 请求图标时返回favicon.ico
- // mw.AddCrossOriginHeaders(), // 添加跨域头
- // mw.HandleOptionsMethod(), // Options和Head请求处理
- //)
- // 设置404、405响应
- router.NoMethod(func(c *gin.Context) {
- resp := wph.E(http.StatusMethodNotAllowed, "Method Not Allowed", nil)
- resp.HttpStatus = http.StatusMethodNotAllowed
- c.JSON(http.StatusBadRequest, wph.E(400, "Method Not Allowed", resp))
- return
- })
- router.NoRoute(func(c *gin.Context) {
- resp := wph.E(http.StatusMethodNotAllowed, "Endpoint Not Found", nil)
- resp.HttpStatus = http.StatusMethodNotAllowed
- c.JSON(http.StatusBadRequest, wph.E(400, "Endpoint Not Found", resp))
- return
- })
- // 注册路由
- router.GET("/test", testBlue)
- // 开始监听HTTP请求
- httpServer := &http.Server{Addr: ":8080", Handler: router}
- go func(httpServer *http.Server) {
- logB.Info("Start http server")
- if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
- logB.Error("http server failed to listen and serve", err.Error())
- }
- }(httpServer)
- serverImpl.SignalHandler(httpServer)
- }
- func testBlue(ctxt *gin.Context) {
- input, _ := ctxt.GetQuery("in")
- serviceConn, err := grpc.Dial("grpc-example:50051", grpc.WithInsecure())
- if err != nil {
- logB.Error("did not connect", err.Error())
- }
- defer func() {
- _ = serviceConn.Close()
- }()
- hwc := example.NewFormatDataClient(serviceConn)
- var resp string
- resp, err = clientImpl.Call(hwc, fmt.Sprintf("Hello %s", input))
- if nil != err {
- logB.Error("call grpc backend failed", err.Error())
- ctxt.JSON(http.StatusBadRequest, wph.E(400, err.Error(), err.Error()))
- return
- }
- ctxt.JSON(http.StatusOK, wph.R(resp))
- }
|