-
Notifications
You must be signed in to change notification settings - Fork 17
/
utils.go
70 lines (54 loc) · 1.27 KB
/
utils.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Created by @menduo @ 2019-01-24
package gobaidumap
import (
"encoding/json"
"io/ioutil"
"net/http"
"os"
"errors"
)
// GetDefaultAK 获取默认的 ak
func GetDefaultAK() string {
ak := defaultAppKey // baidu's
if value, has := os.LookupEnv("GOBAIDUMAP_AK"); has {
ak = value
}
return ak
}
// requestBaidu 构建 HTTP 请求
func requestBaidu(reqType, reqURL string) (interface{}, error) {
res, err := getResStruct(reqType)
if err != nil {
return res, err
}
httpClient := http.Client{}
resp, err := httpClient.Get(reqURL)
if err != nil {
return res, err
}
defer resp.Body.Close()
bytes, _ := ioutil.ReadAll(resp.Body)
if resp.StatusCode == 200 {
err := json.Unmarshal(bytes, &res)
if err != nil {
return res, err
}
} else {
return res, errors.New("请求百度API失败,状态码不等于200")
}
return res, nil
}
// getResStruct 处理百度 API 返回数据,映射到结构体中
func getResStruct(reqType string) (interface{}, error) {
var res interface{}
if reqType == "GetAddressViaIP" {
return new(StructIPToAddress), nil
}
if reqType == "GetGeoViaAddress" {
return new(StructAddressToGEO), nil
}
if reqType == "GetAddressViaGEO" {
return new(StructGEOToAddress), nil
}
return res, errors.New("结构体请求错误")
}