gateway.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package gateway
  2. import (
  3. "git.sxidc.com/go-framework/baize/framework/core/api"
  4. "git.sxidc.com/go-tools/utils/http_client"
  5. )
  6. // Gateway 网关结构
  7. type Gateway struct {
  8. api *api.Api
  9. httpClient *http_client.Client
  10. options *Options
  11. }
  12. // NewGateway 创建网关
  13. // 参数:
  14. // - api: 网关使用的白泽API
  15. // - opts: 选项
  16. // 返回值:
  17. // - 网关
  18. func NewGateway(api *api.Api, opts ...Option) *Gateway {
  19. options := new(Options)
  20. for _, opt := range opts {
  21. opt(options)
  22. }
  23. if options.httpClientTimeoutSec == 0 {
  24. options.httpClientTimeoutSec = 30
  25. }
  26. return &Gateway{
  27. api: api,
  28. httpClient: http_client.New(),
  29. options: options,
  30. }
  31. }
  32. // DestroyGateway 销毁网关
  33. // 参数:
  34. // - gw: 网关
  35. // 返回值: 无
  36. func DestroyGateway(gw *Gateway) {
  37. if gw == nil {
  38. return
  39. }
  40. gw.api = nil
  41. gw = nil
  42. }
  43. // NewBuilder 创建网关API的Builder
  44. // 参数:
  45. // - routerType: 路由类型,有两种
  46. // - api.RouterRoot: 根路由
  47. // - api.RouterPrefix: 带url前缀的路由
  48. //
  49. // - version: 版本,用于获取基于上面两中路由够造的带有版本号的路由,传空字符串则选定上面两种路由本身
  50. // - middlewares: 该Builder范围的中间件
  51. // 返回值:
  52. // - 网关API的Builder
  53. func (gw *Gateway) NewBuilder(routerType string, version string, middlewares ...Handler) *Builder {
  54. return newBuilder(gw.api.ChooseRouter(routerType, version), gw.httpClient, gw.options.httpClientTimeoutSec, middlewares...)
  55. }
  56. type Option func(options *Options)
  57. type Options struct {
  58. httpClientTimeoutSec int64
  59. }
  60. // WithHttpClientTimeoutSec 设置http客户端的超时时间
  61. func WithHttpClientTimeoutSec(httpClientTimeoutSec int64) Option {
  62. return func(options *Options) {
  63. options.httpClientTimeoutSec = httpClientTimeoutSec
  64. }
  65. }