12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- package main
- import (
- "bytes"
- "encoding/json"
- "io"
- "net/http"
- "reflect"
- "sort"
- "time"
- )
- // IsInStringArray 判断数组中是否存在字符串
- func IsInStringArray(str string, arr []string) bool {
- // 先对字符串数组进行排序
- sort.Strings(arr)
- // 使用二分查找算法查找字符串
- pos := sort.SearchStrings(arr, str)
- // 如果找到了则返回 true,否则返回 false
- return pos < len(arr) && arr[pos] == str
- }
- // structToMap 结构体转map
- func structToMap(obj interface{}) map[string]interface{} {
- result := make(map[string]interface{})
- v := reflect.ValueOf(obj)
- t := reflect.TypeOf(obj)
- // Ensure the input is a struct
- if t.Kind() == reflect.Ptr {
- t = t.Elem()
- v = v.Elem()
- }
- if t.Kind() != reflect.Struct {
- return nil
- }
- for i := 0; i < t.NumField(); i++ {
- field := t.Field(i)
- value := v.Field(i)
- // Use the JSON tag if available
- tag := field.Tag.Get("json")
- if tag == "" {
- tag = field.Name
- }
- result[tag] = value.Interface()
- }
- return result
- }
- // GetAreaInfo 调用抽取接口,获取省市区
- func GetAreaInfo(data map[string]interface{}) map[string]interface{} {
- info := map[string]interface{}{}
- client := &http.Client{Timeout: 2 * time.Second}
- jsonStr, _ := json.Marshal(data)
- resp, err := client.Post("http://127.0.0.1:9996/service/region", "application/json", bytes.NewBuffer(jsonStr))
- if err != nil {
- return info
- }
- res, err := io.ReadAll(resp.Body)
- if err != nil {
- return info
- }
- err = json.Unmarshal(res, &info)
- if err != nil {
- return info
- }
- return info
- }
|