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
| type Resp struct { Code int `json:"code"` Msg string `json:"msg"` Time int `json:"time"` Data interface{} `json:"data"` }
type Article struct { Title string `json:"title"` Content string `json:"content"` }
func handle() { b, err := request("GET", "/api/article", nil) if err != nil { panic(fmt.Errorf("get article error: %v\n", err)) } var res1 Resp var article Article json.Unmarshal(b, &res1) articleByte, err := json.Marshal(res1.Data) if err != nil { panic(fmt.Errorf("marshal resp data error: %v\n", err)) } json.Unmarshal(articleByte, article) fmt.Printf("Title: %s, Content: %s\n", article.Title, article.Content)
}
func request(method, url string, params map[string]interface{}) (b []byte, err error) { jsonData, err := json.Marshal(params) if err != nil { return } client := &http.Client{} req, err := http.NewRequest(method, url, bytes.NewReader(jsonData)) if err != nil { return } if strings.ToUpper(method) == "GET" { q := req.URL.Query() for key, val := range params { q.Add(key, val.(string)) } req.URL.RawQuery = q.Encode() }
resp, err := client.Do(req) if err != nil { return nil, fmt.Errorf("request failed: %v", err) }
defer func(Body io.ReadCloser) { _ = Body.Close() }(resp.Body)
b, err = io.ReadAll(resp.Body) if err != nil { return nil, fmt.Errorf("read response body failed: %v", err) }
return }
|