server

  1. func main() {
  2. // http://127.0.0.1/add?a=1&b=2
  3. http.HandleFunc("/add", func(w http.ResponseWriter, req *http.Request) {
  4. // 1.获取参数
  5. _ = req.ParseForm()
  6. fmt.Println("path: ", req.URL.Path)
  7. // 2.反序列化
  8. a, _ := strconv.Atoi(req.Form["a"][0])
  9. b, _ := strconv.Atoi(req.Form["b"][0])
  10. w.Header().Set("Content-Type", "application/json")
  11. jData, _ := json.Marshal(map[string]int{
  12. "data": a + b,
  13. })
  14. _, _ = w.Write(jData)
  15. })
  16. http.ListenAndServe(":8080", nil)
  17. }

client

  1. func main() {
  2. // http包
  3. client := http.Client{}
  4. res, _ := client.Get("http://localhost:8080/add?a=10&b=6")
  5. ct := res.Header.Get("Content-Type")
  6. date := res.Header.Get("Date")
  7. fmt.Println("ct: ", ct)
  8. fmt.Println("date: ", date)
  9. url := res.Request.URL
  10. code := res.StatusCode
  11. status := res.Status
  12. fmt.Println("url: ", url)
  13. fmt.Println("code: ", code)
  14. fmt.Println("status: ", status)
  15. body := res.Body
  16. readBodyStr, _ := ioutil.ReadAll(body)
  17. fmt.Println("readBodyStr: ", string(readBodyStr))
  18. }