api.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. package api
  2. import (
  3. "context"
  4. "git.sxidc.com/go-tools/utils/strutils"
  5. "git.sxidc.com/service-supports/fserr"
  6. "github.com/gin-gonic/gin"
  7. "net/http"
  8. )
  9. type Api struct {
  10. options Options
  11. server *http.Server
  12. rootRouter *RootRouter
  13. prefixRouter *PrefixRouter
  14. }
  15. func New(opts ...Option) *Api {
  16. options := new(Options)
  17. for _, opt := range opts {
  18. opt(options)
  19. }
  20. if strutils.IsStringEmpty(options.port) {
  21. options.port = "8080"
  22. }
  23. engine := gin.New()
  24. server := &http.Server{
  25. Addr: ":" + options.port,
  26. Handler: engine,
  27. }
  28. api := &Api{
  29. options: *options,
  30. server: server,
  31. rootRouter: newRootRouter(engine),
  32. }
  33. if strutils.IsStringNotEmpty(options.urlPrefix) {
  34. api.prefixRouter = newPrefixRouter(engine.Group(options.urlPrefix))
  35. }
  36. return api
  37. }
  38. func NewWithEngine(server *http.Server, engine *gin.Engine, opts ...Option) *Api {
  39. options := new(Options)
  40. for _, opt := range opts {
  41. opt(options)
  42. }
  43. if strutils.IsStringEmpty(options.port) {
  44. options.port = "8080"
  45. }
  46. api := &Api{
  47. options: *options,
  48. server: server,
  49. rootRouter: newRootRouter(engine),
  50. }
  51. if strutils.IsStringNotEmpty(options.urlPrefix) {
  52. api.prefixRouter = newPrefixRouter(engine.Group(options.urlPrefix))
  53. }
  54. return api
  55. }
  56. func (api *Api) Start() error {
  57. err := api.server.ListenAndServe()
  58. if err != nil && !fserr.Is(err, http.ErrServerClosed) {
  59. return err
  60. }
  61. return nil
  62. }
  63. func (api *Api) Finish() error {
  64. return api.server.Shutdown(context.Background())
  65. }
  66. func (api *Api) Options() Options {
  67. return api.options
  68. }
  69. func (api *Api) RootRouter() Router {
  70. return api.rootRouter
  71. }
  72. func (api *Api) PrefixRouter() Router {
  73. if api.prefixRouter == nil {
  74. return api.rootRouter
  75. }
  76. return api.prefixRouter
  77. }
  78. const (
  79. RouterRoot = "root"
  80. RouterPrefix = "prefix"
  81. )
  82. func (api *Api) ChooseRouter(routerType string, version string) Router {
  83. var router Router
  84. switch routerType {
  85. case RouterRoot:
  86. router = api.RootRouter()
  87. case RouterPrefix:
  88. router = api.PrefixRouter()
  89. default:
  90. router = api.PrefixRouter()
  91. }
  92. if strutils.IsStringNotEmpty(version) {
  93. router = router.VersionedRouter(version)
  94. }
  95. return router
  96. }