format.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package geoip
  2. import "strings"
  3. // FormatRegion 将 ip2region 原始串格式化为客服可读位置(最长约 200 字符)。
  4. // 原始格式:国家|省份|城市|ISP|国家代码
  5. func FormatRegion(raw string) string {
  6. raw = strings.TrimSpace(raw)
  7. if raw == "" {
  8. return ""
  9. }
  10. parts := strings.Split(raw, "|")
  11. for i := range parts {
  12. parts[i] = strings.TrimSpace(parts[i])
  13. }
  14. if len(parts) == 0 {
  15. return ""
  16. }
  17. country := ""
  18. province := ""
  19. city := ""
  20. isp := ""
  21. if len(parts) > 0 {
  22. country = parts[0]
  23. }
  24. if len(parts) > 1 {
  25. province = parts[1]
  26. }
  27. if len(parts) > 2 {
  28. city = parts[2]
  29. }
  30. if len(parts) > 3 {
  31. isp = parts[3]
  32. }
  33. // 中国:省略国家,优先「省·市」,运营商单独括号
  34. if country == "中国" || country == "China" {
  35. loc := joinNonEmpty("·", province, city)
  36. if loc == "" {
  37. loc = country
  38. }
  39. if isp != "" && isp != "0" {
  40. return trimToMax(loc+" ("+isp+")", 200)
  41. }
  42. return trimToMax(loc, 200)
  43. }
  44. loc := joinNonEmpty(" · ", country, province, city)
  45. if loc == "" {
  46. loc = country
  47. }
  48. if isp != "" && isp != "0" {
  49. return trimToMax(loc+" ("+isp+")", 200)
  50. }
  51. return trimToMax(loc, 200)
  52. }
  53. func joinNonEmpty(sep string, items ...string) string {
  54. var out []string
  55. for _, s := range items {
  56. s = strings.TrimSpace(s)
  57. if s == "" || s == "0" {
  58. continue
  59. }
  60. out = append(out, s)
  61. }
  62. return strings.Join(out, sep)
  63. }
  64. func trimToMax(s string, max int) string {
  65. if len(s) <= max {
  66. return s
  67. }
  68. return s[:max]
  69. }