123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- package main
- import (
- "../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"
- "net/http"
- "net/url"
- )
- // Istio测试用,HTTP边界服务,同时也是后端服务的客户端
- var log2 *logger.Logger
- func main() {
- log2 = logger.New()
- log2.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", testV2)
- // 开始监听HTTP请求
- httpServer := &http.Server{Addr: ":8080", Handler: router}
- go func(httpServer *http.Server) {
- log2.Info("Start http server")
- if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
- log2.Error("http server failed to listen and serve", err.Error())
- }
- }(httpServer)
- serverImpl.SignalHandler(httpServer)
- }
- func testV2(ctxt *gin.Context) {
- input, _ := ctxt.GetQuery("in")
- uri := fmt.Sprintf("http://http-backend:8080/backend?in=%s", url.QueryEscape(fmt.Sprintf("Hello %s", input)))
- resp, err := wph.JSONRequest().Call(http.MethodGet, uri, nil)
- if nil != err {
- log2.Error("call http backend failed", err.Error())
- ctxt.JSON(http.StatusBadRequest, wph.E(400, err.Error(), err.Error()))
- return
- }
- ctxt.String(http.StatusOK, string(resp))
- }
|