http_init.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package http_binding
  2. import (
  3. "context"
  4. "errors"
  5. "git.sxidc.com/go-tools/api_binding/http_binding/binding_context"
  6. "git.sxidc.com/go-tools/api_binding/http_binding/middleware"
  7. "git.sxidc.com/service-supports/fslog"
  8. "github.com/gin-gonic/gin"
  9. "net/http"
  10. "time"
  11. )
  12. var (
  13. urlPrefix string
  14. )
  15. var serverInstance *http.Server
  16. var routerInstance *gin.Engine
  17. func Init(apiUrlPrefix string, port string) {
  18. urlPrefix = apiUrlPrefix
  19. routerInstance = gin.New()
  20. routerInstance.Use(fslog.GinLogger([]string{"/" + urlPrefix + "/api/version"}), fslog.GinRecovery(),
  21. func(c *gin.Context) { middleware.Cors()(&binding_context.Context{Context: c}) },
  22. func(c *gin.Context) { middleware.ReadRequestBodyData()(&binding_context.Context{Context: c}) })
  23. serverInstance = &http.Server{
  24. Addr: ":" + port,
  25. Handler: routerInstance,
  26. }
  27. go func() {
  28. if err := serverInstance.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
  29. panic(err)
  30. }
  31. }()
  32. }
  33. func Destroy() {
  34. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  35. defer cancel()
  36. if err := serverInstance.Shutdown(ctx); err != nil {
  37. panic(err)
  38. }
  39. }
  40. func GetRouter() *gin.Engine {
  41. return routerInstance
  42. }