api.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. }
  24. func DestroyGateway() {
  25. if appInstance == nil {
  26. return
  27. }
  28. gateway.DestroyGateway(gatewayInstance)
  29. gatewayInstance = nil
  30. baize.DestroyApplication(appInstance)
  31. appInstance = nil
  32. }
  33. func Start() error {
  34. // 初始化路由
  35. for _, router := range RegisteredRouters {
  36. router.Init(gatewayInstance)
  37. }
  38. err := appInstance.Start()
  39. if err != nil {
  40. return err
  41. }
  42. return nil
  43. }
  44. func Finish() error {
  45. err := appInstance.Finish()
  46. if err != nil {
  47. return err
  48. }
  49. return nil
  50. }
  51. func ServerHttpForTest(w http.ResponseWriter, req *http.Request) {
  52. appInstance.Api().RootRouter().(*api.RootRouter).ServerHttp(w, req)
  53. }
  54. type Router interface {
  55. Init(gw *gateway.Gateway)
  56. }
  57. var RegisteredRouters = []Router{
  58. &root.Router{},
  59. &v1.Router{},
  60. }