tools.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package main
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "io"
  6. "net/http"
  7. "reflect"
  8. "sort"
  9. "time"
  10. )
  11. // IsInStringArray 判断数组中是否存在字符串
  12. func IsInStringArray(str string, arr []string) bool {
  13. // 先对字符串数组进行排序
  14. sort.Strings(arr)
  15. // 使用二分查找算法查找字符串
  16. pos := sort.SearchStrings(arr, str)
  17. // 如果找到了则返回 true,否则返回 false
  18. return pos < len(arr) && arr[pos] == str
  19. }
  20. // structToMap 结构体转map
  21. func structToMap(obj interface{}) map[string]interface{} {
  22. result := make(map[string]interface{})
  23. v := reflect.ValueOf(obj)
  24. t := reflect.TypeOf(obj)
  25. // Ensure the input is a struct
  26. if t.Kind() == reflect.Ptr {
  27. t = t.Elem()
  28. v = v.Elem()
  29. }
  30. if t.Kind() != reflect.Struct {
  31. return nil
  32. }
  33. for i := 0; i < t.NumField(); i++ {
  34. field := t.Field(i)
  35. value := v.Field(i)
  36. // Use the JSON tag if available
  37. tag := field.Tag.Get("json")
  38. if tag == "" {
  39. tag = field.Name
  40. }
  41. result[tag] = value.Interface()
  42. }
  43. return result
  44. }
  45. // GetAreaInfo 调用抽取接口,获取省市区
  46. func GetAreaInfo(data map[string]interface{}) map[string]interface{} {
  47. info := map[string]interface{}{}
  48. client := &http.Client{Timeout: 2 * time.Second}
  49. jsonStr, _ := json.Marshal(data)
  50. resp, err := client.Post("http://127.0.0.1:9996/service/region", "application/json", bytes.NewBuffer(jsonStr))
  51. if err != nil {
  52. return info
  53. }
  54. res, err := io.ReadAll(resp.Body)
  55. if err != nil {
  56. return info
  57. }
  58. err = json.Unmarshal(res, &info)
  59. if err != nil {
  60. return info
  61. }
  62. return info
  63. }