package api import ( "context" "git.sxidc.com/go-tools/utils/strutils" "git.sxidc.com/service-supports/fserr" "github.com/gin-gonic/gin" "net/http" ) type Api struct { options Options server *http.Server rootRouter *RootRouter prefixRouter *PrefixRouter } func New(opts ...Option) *Api { options := new(Options) for _, opt := range opts { opt(options) } if strutils.IsStringEmpty(options.port) { options.port = "8080" } engine := gin.New() server := &http.Server{ Addr: ":" + options.port, Handler: engine, } api := &Api{ options: *options, server: server, rootRouter: newRootRouter(engine), } if strutils.IsStringNotEmpty(options.urlPrefix) { api.prefixRouter = newPrefixRouter(engine.Group(options.urlPrefix)) } return api } func (api *Api) Start() error { err := api.server.ListenAndServe() if err != nil && !fserr.Is(err, http.ErrServerClosed) { return err } return nil } func (api *Api) Finish() error { return api.server.Shutdown(context.Background()) } func (api *Api) Options() Options { return api.options } func (api *Api) RootRouter() Router { return api.rootRouter } func (api *Api) PrefixRouter() Router { if api.prefixRouter == nil { return api.rootRouter } return api.prefixRouter }