http_endpoint_v1.go 2.4 KB

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