http_endpoint_v2.go 2.0 KB

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