http_endpoint_blue.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package main
  2. import (
  3. "../clientImpl"
  4. "../example"
  5. "../serverImpl"
  6. "fmt"
  7. "git.wanpinghui.com/WPH/go_common/wph"
  8. "git.wanpinghui.com/WPH/go_common/wph/logger"
  9. "github.com/gin-gonic/gin"
  10. "github.com/sirupsen/logrus"
  11. "google.golang.org/grpc"
  12. "net/http"
  13. )
  14. // HTTP边界服务,同时也是后端服务的客户端
  15. // Istio对比测试用,部署于无Istio的环境
  16. var logB *logger.Logger
  17. func main() {
  18. logB = logger.New()
  19. logB.Level = logrus.WarnLevel
  20. router := gin.New()
  21. // 添加 GIN 请求处理中间件
  22. //router.Use(
  23. // gzip.Gzip(gzip.DefaultCompression),
  24. // mw.Favicon("./static/favicon.ico"), // 请求图标时返回favicon.ico
  25. // mw.AddCrossOriginHeaders(), // 添加跨域头
  26. // mw.HandleOptionsMethod(), // Options和Head请求处理
  27. //)
  28. // 设置404、405响应
  29. router.NoMethod(func(c *gin.Context) {
  30. resp := wph.E(http.StatusMethodNotAllowed, "Method Not Allowed", nil)
  31. resp.HttpStatus = http.StatusMethodNotAllowed
  32. c.JSON(http.StatusBadRequest, wph.E(400, "Method Not Allowed", resp))
  33. return
  34. })
  35. router.NoRoute(func(c *gin.Context) {
  36. resp := wph.E(http.StatusMethodNotAllowed, "Endpoint Not Found", nil)
  37. resp.HttpStatus = http.StatusMethodNotAllowed
  38. c.JSON(http.StatusBadRequest, wph.E(400, "Endpoint Not Found", resp))
  39. return
  40. })
  41. // 注册路由
  42. router.GET("/test", testBlue)
  43. // 开始监听HTTP请求
  44. httpServer := &http.Server{Addr: ":8080", Handler: router}
  45. go func(httpServer *http.Server) {
  46. logB.Info("Start http server")
  47. if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
  48. logB.Error("http server failed to listen and serve", err.Error())
  49. }
  50. }(httpServer)
  51. serverImpl.SignalHandler(httpServer)
  52. }
  53. func testBlue(ctxt *gin.Context) {
  54. input, _ := ctxt.GetQuery("in")
  55. serviceConn, err := grpc.Dial("grpc-example:50051", grpc.WithInsecure())
  56. if err != nil {
  57. logB.Error("did not connect", err.Error())
  58. }
  59. defer func() {
  60. _ = serviceConn.Close()
  61. }()
  62. hwc := example.NewFormatDataClient(serviceConn)
  63. var resp string
  64. resp, err = clientImpl.Call(hwc, fmt.Sprintf("Hello %s", input))
  65. if nil != err {
  66. logB.Error("call grpc backend failed", err.Error())
  67. ctxt.JSON(http.StatusBadRequest, wph.E(400, err.Error(), err.Error()))
  68. return
  69. }
  70. ctxt.JSON(http.StatusOK, wph.R(resp))
  71. }