region_options_handler.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. package handlers
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "net/http"
  7. "sort"
  8. "sync"
  9. "time"
  10. "cmr-backend/internal/apperr"
  11. "cmr-backend/internal/httpx"
  12. )
  13. type RegionOptionsHandler struct {
  14. client *http.Client
  15. mu sync.Mutex
  16. cache []regionProvince
  17. }
  18. type regionProvince struct {
  19. Code string `json:"code"`
  20. Name string `json:"name"`
  21. Cities []regionCity `json:"cities"`
  22. }
  23. type regionCity struct {
  24. Code string `json:"code"`
  25. Name string `json:"name"`
  26. }
  27. type remoteProvince struct {
  28. Code string `json:"code"`
  29. Name string `json:"name"`
  30. }
  31. type remoteCity struct {
  32. Code string `json:"code"`
  33. Name string `json:"name"`
  34. Province string `json:"province"`
  35. }
  36. func NewRegionOptionsHandler() *RegionOptionsHandler {
  37. return &RegionOptionsHandler{
  38. client: &http.Client{Timeout: 12 * time.Second},
  39. }
  40. }
  41. func (h *RegionOptionsHandler) Get(w http.ResponseWriter, r *http.Request) {
  42. items, err := h.load(r.Context())
  43. if err != nil {
  44. httpx.WriteError(w, err)
  45. return
  46. }
  47. httpx.WriteJSON(w, http.StatusOK, map[string]any{"data": items})
  48. }
  49. func (h *RegionOptionsHandler) load(ctx context.Context) ([]regionProvince, error) {
  50. h.mu.Lock()
  51. if len(h.cache) > 0 {
  52. cached := h.cache
  53. h.mu.Unlock()
  54. return cached, nil
  55. }
  56. h.mu.Unlock()
  57. // Data source:
  58. // https://github.com/uiwjs/province-city-china
  59. // Using province + city JSON only, then reducing to the province/city structure
  60. // needed by ops workbench location management.
  61. provinces, err := h.fetchProvinces(ctx, "https://unpkg.com/province-city-china/dist/province.json")
  62. if err != nil {
  63. return nil, err
  64. }
  65. cities, err := h.fetchCities(ctx, "https://unpkg.com/province-city-china/dist/city.json")
  66. if err != nil {
  67. return nil, err
  68. }
  69. cityMap := make(map[string][]regionCity)
  70. for _, item := range cities {
  71. if item.Province == "" || item.Code == "" {
  72. continue
  73. }
  74. fullCode := item.Province + item.Code + "00"
  75. cityMap[item.Province] = append(cityMap[item.Province], regionCity{
  76. Code: fullCode,
  77. Name: item.Name,
  78. })
  79. }
  80. for key := range cityMap {
  81. sort.Slice(cityMap[key], func(i, j int) bool { return cityMap[key][i].Code < cityMap[key][j].Code })
  82. }
  83. items := make([]regionProvince, 0, len(provinces))
  84. for _, item := range provinces {
  85. if len(item.Code) < 2 {
  86. continue
  87. }
  88. provinceCode := item.Code[:2]
  89. province := regionProvince{
  90. Code: item.Code,
  91. Name: item.Name,
  92. }
  93. if entries := cityMap[provinceCode]; len(entries) > 0 {
  94. province.Cities = entries
  95. } else {
  96. // 直辖市 / 特殊地区没有单独的地级市列表时,退化成自身即可。
  97. province.Cities = []regionCity{{
  98. Code: item.Code,
  99. Name: item.Name,
  100. }}
  101. }
  102. items = append(items, province)
  103. }
  104. h.mu.Lock()
  105. h.cache = items
  106. h.mu.Unlock()
  107. return items, nil
  108. }
  109. func (h *RegionOptionsHandler) fetchProvinces(ctx context.Context, url string) ([]remoteProvince, error) {
  110. req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
  111. if err != nil {
  112. return nil, apperr.New(http.StatusBadGateway, "region_source_unavailable", "省市数据源不可用")
  113. }
  114. resp, err := h.client.Do(req)
  115. if err != nil {
  116. return nil, apperr.New(http.StatusBadGateway, "region_source_unavailable", "省市数据源不可用")
  117. }
  118. defer resp.Body.Close()
  119. if resp.StatusCode != http.StatusOK {
  120. return nil, apperr.New(http.StatusBadGateway, "region_source_unavailable", fmt.Sprintf("省级数据拉取失败: %d", resp.StatusCode))
  121. }
  122. var items []remoteProvince
  123. if err := json.NewDecoder(resp.Body).Decode(&items); err != nil {
  124. return nil, apperr.New(http.StatusBadGateway, "region_source_invalid", "省级数据格式无效")
  125. }
  126. return items, nil
  127. }
  128. func (h *RegionOptionsHandler) fetchCities(ctx context.Context, url string) ([]remoteCity, error) {
  129. req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
  130. if err != nil {
  131. return nil, apperr.New(http.StatusBadGateway, "region_source_unavailable", "省市数据源不可用")
  132. }
  133. resp, err := h.client.Do(req)
  134. if err != nil {
  135. return nil, apperr.New(http.StatusBadGateway, "region_source_unavailable", "省市数据源不可用")
  136. }
  137. defer resp.Body.Close()
  138. if resp.StatusCode != http.StatusOK {
  139. return nil, apperr.New(http.StatusBadGateway, "region_source_unavailable", fmt.Sprintf("市级数据拉取失败: %d", resp.StatusCode))
  140. }
  141. var items []remoteCity
  142. if err := json.NewDecoder(resp.Body).Decode(&items); err != nil {
  143. return nil, apperr.New(http.StatusBadGateway, "region_source_invalid", "市级数据格式无效")
  144. }
  145. return items, nil
  146. }