api.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 (api *Api) Start() error {
  39. err := api.server.ListenAndServe()
  40. if err != nil && !fserr.Is(err, http.ErrServerClosed) {
  41. return err
  42. }
  43. return nil
  44. }
  45. func (api *Api) Finish() error {
  46. return api.server.Shutdown(context.Background())
  47. }
  48. func (api *Api) Options() Options {
  49. return api.options
  50. }
  51. func (api *Api) RootRouter() Router {
  52. return api.rootRouter
  53. }
  54. func (api *Api) PrefixRouter() Router {
  55. if api.prefixRouter == nil {
  56. return api.rootRouter
  57. }
  58. return api.prefixRouter
  59. }