http_init.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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"}),
  21. fslog.GinRecovery(),
  22. func(c *gin.Context) { middleware.Cors()(&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 GetServer() *http.Server {
  41. return serverInstance
  42. }
  43. func GetRouter() *gin.Engine {
  44. return routerInstance
  45. }