http_backend.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package main
  2. import (
  3. "../serverImpl"
  4. "fmt"
  5. "git.wanpinghui.com/WPH/go_common/wph"
  6. "github.com/gin-gonic/gin"
  7. "net/http"
  8. )
  9. // Istio测试用,HTTP后端服务
  10. func main() {
  11. router := gin.New()
  12. // 添加 GIN 请求处理中间件
  13. //router.Use(
  14. // gzip.Gzip(gzip.DefaultCompression),
  15. // mw.Favicon("./static/favicon.ico"), // 请求图标时返回favicon.ico
  16. // mw.AddCrossOriginHeaders(), // 添加跨域头
  17. // mw.HandleOptionsMethod(), // Options和Head请求处理
  18. //)
  19. // 设置404、405响应
  20. router.NoMethod(func(c *gin.Context) {
  21. resp := wph.E(http.StatusMethodNotAllowed, "Method Not Allowed", nil)
  22. resp.HttpStatus = http.StatusMethodNotAllowed
  23. panic(resp)
  24. })
  25. router.NoRoute(func(c *gin.Context) {
  26. resp := wph.E(http.StatusMethodNotAllowed, "Endpoint Not Found", nil)
  27. resp.HttpStatus = http.StatusMethodNotAllowed
  28. panic(resp)
  29. })
  30. // 注册路由
  31. router.GET("/backend", backend)
  32. // 开始监听HTTP请求
  33. httpServer := &http.Server{Addr: ":8080", Handler: router}
  34. go func(httpServer *http.Server) {
  35. println("Start http server")
  36. if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
  37. println("http server failed to listen and serve", err.Error())
  38. }
  39. }(httpServer)
  40. serverImpl.SignalHandler(httpServer)
  41. }
  42. func backend(ctxt *gin.Context) {
  43. input, _ := ctxt.GetQuery("in")
  44. var ipStr string
  45. ip, err := wph.PrivateIPv4()
  46. if nil == err && nil != ip {
  47. ipStr = ip.String()
  48. }
  49. ctxt.JSON(http.StatusOK, wph.R(fmt.Sprintf("%s (from %s:8080)", input, ipStr)))
  50. }