go``中使用占位符、net用法

go``中使用占位符、net用法

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

//{{.Itemname}}两个中括号

import (
"strconv"
"text/template"
"strings"
)
type Test struct {
Name string
Token string
}
func Format(placedata interface{}, data string) string {
s := new(strings.Builder)
temp, _ := template.New("tplname").Parse(data)
err := temp.Execute(s, placedata)
if err != nil {
panic(err)
}
return s.String()
}
haha := `
{
"name": "{{.Name}}",
"test": "{{.Token}}"
}`
data := ItemTestdata{"你好哦哦哦AA", "我佛了"}
postdata := Format(data, haha)
1
2
3
4
//空接口不可以直接引用,要先判定类型
//通过.(stirng)或者.([]interface{})等来判定字符串或者切片等
var result1 map[string]interface{}
test_id, _ := result1["objectId"].(string)
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
//"net/http"的使用
func Get(yoururl string, data map[string]string) map[string]interface{} {
request, err := http.NewRequest("GET", yoururl, nil)
if err != nil {
log.Println("err->", err)
}
//加入get参数
q := request.URL.Query()
for key, value := range data {
q.Add(key, value)
}
request.URL.RawQuery = q.Encode()
resp, err := http.DefaultClient.Do(request)
if err != nil {
log.Println("err->", err)
}
defer resp.Body.Close()
data1, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Println("err->", err)
}
rdata := string(data1)
result := make(map[string]interface{})
err1 := json.Unmarshal([]byte(rdata), &result)
if err1 != nil {
fmt.Println(err)
}
// log.Print("GET请求 ", request.URL, " ", resp.Status)
return result

}
func Post(yoururl string, data string, yourheader map[string]string) (map[string]interface{}, *http.Response) {
data2 := strings.NewReader(data)
request, err := http.NewRequest("POST", yoururl, data2)
for key, value := range yourheader {
request.Header.Set(key, value)
}
// request.Header.Set("Content-Type", "text/plain")
if err != nil {
log.Println("err->", err)
}
resp1, err := http.DefaultClient.Do(request)
if err != nil {
log.Println("err->", err)
}
defer resp1.Body.Close()
data1, err := ioutil.ReadAll(resp1.Body)
if err != nil {
log.Println("err->", err)
}
rdata := string(data1)
//转成map为了后续方便用
result := make(map[string]interface{})
err1 := json.Unmarshal([]byte(rdata), &result)
if err1 != nil {
fmt.Println(err)
}
return result, resp1
}


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!