api.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package api
  2. import (
  3. "baize-demo/project/gateway/api/root"
  4. "baize-demo/project/gateway/api/v1"
  5. "baize-demo/project/gateway/config"
  6. "git.sxidc.com/go-framework/baize"
  7. "git.sxidc.com/go-framework/baize/framework/core/api"
  8. "git.sxidc.com/go-framework/baize/framework/core/application"
  9. "git.sxidc.com/go-framework/baize/framework/gateway"
  10. "net/http"
  11. )
  12. var appInstance *application.App
  13. var gatewayInstance *gateway.Gateway
  14. func NewGateway() {
  15. if appInstance != nil {
  16. return
  17. }
  18. appInstance = baize.NewApplication(config.GetConfig().ApplicationConfig)
  19. // 注册Router
  20. appInstance.Api().PrefixRouter().RegisterVersionedRouter("v1")
  21. // 创建gateway
  22. gatewayInstance = gateway.NewGateway(appInstance.Api())
  23. // 启动Version
  24. appInstance.Api().PrefixRouter().AddRoute(http.MethodGet, "/version", func(c *api.Context) {
  25. c.JSON(http.StatusOK, map[string]any{
  26. "version": "v1.0.0",
  27. })
  28. })
  29. }
  30. func DestroyGateway() {
  31. if appInstance == nil {
  32. return
  33. }
  34. gateway.DestroyGateway(gatewayInstance)
  35. gatewayInstance = nil
  36. baize.DestroyApplication(appInstance)
  37. appInstance = nil
  38. }
  39. func Start() error {
  40. // 初始化路由
  41. for _, router := range RegisteredRouters {
  42. router.Init(gatewayInstance)
  43. }
  44. err := appInstance.Start()
  45. if err != nil {
  46. return err
  47. }
  48. return nil
  49. }
  50. func Finish() error {
  51. err := appInstance.Finish()
  52. if err != nil {
  53. return err
  54. }
  55. return nil
  56. }
  57. func ServerHttpForTest(w http.ResponseWriter, req *http.Request) {
  58. appInstance.Api().RootRouter().(*api.RootRouter).ServerHttp(w, req)
  59. }
  60. type Router interface {
  61. Init(gw *gateway.Gateway)
  62. }
  63. var RegisteredRouters = []Router{
  64. &root.Router{},
  65. &v1.Router{},
  66. }