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
| package main
import ( "bytes" "encoding/json" "fmt" "log" "net/http" )
type msg struct { D int `json:"d"` } type PrintInfo struct { A string `json:"a"` B string `json:"b"` }
func main() { Prints := PrintInfo{ A: "1", B: "2", } marshal, _ := json.Marshal(Prints) resp, err := http.Post("http://localhost:8080", "application/json", bytes.NewBuffer(marshal)) if err != nil { log.Fatalf("无法获取响应: %v", err) } defer resp.Body.Close()
if resp.StatusCode != http.StatusOK { log.Fatalf("服务器返回错误状态码: %d", resp.StatusCode) }
var m msg if err := json.NewDecoder(resp.Body).Decode(&m); err != nil { log.Fatalf("无法解码响应体: %v", err) }
fmt.Println(m.D) }
|