123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- package main
- import (
- "../example"
- "../serverImpl"
- "context"
- "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"
- "google.golang.org/grpc"
- "google.golang.org/grpc/grpclog"
- "net/http"
- "time"
- )
- // Istio测试用,HTTP边界服务,同时也是后端服务的客户端
- var log1 *logger.Logger
- func main() {
- log1 = logger.New()
- log1.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", testV1)
- // 开始监听HTTP请求
- httpServer := &http.Server{Addr: ":8080", Handler: router}
- go func(httpServer *http.Server) {
- log1.Info("Start http server")
- if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
- log1.Error("http server failed to listen and serve", err.Error())
- }
- }(httpServer)
- serverImpl.SignalHandler(httpServer)
- }
- func testV1(ctxt *gin.Context) {
- input, _ := ctxt.GetQuery("in")
- conn, err := grpc.Dial("grpc-example:50051", grpc.WithInsecure())
- if err != nil {
- log1.Error("Did not connect", err.Error())
- }
- defer func() {
- _ = conn.Close()
- }()
- grpclog.SetLoggerV2(log1)
- hwc := example.NewFormatDataClient(conn)
- ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
- defer cancel()
- var resp *example.Data
- resp, err = hwc.DoFormat(ctx, &example.Data{Text: fmt.Sprintf("Hello %s", input)})
- if err != nil {
- log1.Error("call grpc backend failed", err.Error())
- ctxt.JSON(http.StatusBadRequest, wph.E(400, err.Error(), err.Error()))
- return
- }
- ctxt.JSON(http.StatusOK, wph.R(resp.Text))
- }
|