1 简介

Go语言内置的net/http包提供了HTTP客户端和服务端的实现

  1. resp, err := http.Get("http://example.com/")
  2. ...
  3. resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf)
  4. ...
  5. resp, err := http.PostForm("http://example.com/form",
  6. url.Values{"key": {"Value"}, "id": {"123"}})

程序在使用完response后必须关闭回复的主体。

  1. resp, err := http.Get("http://example.com/")
  2. if err != nil {
  3. // handle error
  4. }
  5. defer resp.Body.Close()
  6. body, err := ioutil.ReadAll(resp.Body)
  7. // ...

2 GET请求示例

(1) client.go

  1. func main() {
  2. apiUrl := "http://127.0.0.1:9090/get"
  3. // URL param
  4. data := url.Values{}
  5. data.Set("name", "小王子")
  6. data.Set("age", "18")
  7. u, err := url.ParseRequestURI(apiUrl)
  8. if err != nil {
  9. fmt.Printf("parse url requestUrl failed, err:%v\n", err)
  10. }
  11. u.RawQuery = data.Encode() // URL encode
  12. fmt.Println(u.String())
  13. resp, err := http.Get(u.String())
  14. if err != nil {
  15. fmt.Printf("post failed, err:%v\n", err)
  16. return
  17. }
  18. defer resp.Body.Close()
  19. b, err := ioutil.ReadAll(resp.Body)
  20. if err != nil {
  21. fmt.Printf("get resp failed, err:%v\n", err)
  22. return
  23. }
  24. fmt.Println(string(b))
  25. }

(2) server.go

  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. )
  6. func main() {
  7. http.HandleFunc("/get", getHandler)
  8. _ = http.ListenAndServe("127.0.0.1:9090", nil)
  9. }
  10. func getHandler(w http.ResponseWriter, r *http.Request) {
  11. defer r.Body.Close()
  12. data := r.URL.Query()
  13. fmt.Println(data.Get("name"))
  14. fmt.Println(data.Get("age"))
  15. answer := `{"status": "ok"}`
  16. w.Write([]byte(answer))
  17. }

3 Post请求示例

(1) client.go

  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "net/http"
  6. "strings"
  7. )
  8. // net/http post demo
  9. func main() {
  10. url := "http://127.0.0.1:9090/post"
  11. // 表单数据
  12. //contentType := "application/x-www-form-urlencoded"
  13. //data := "name=小王子&age=18"
  14. // json
  15. contentType := "application/json"
  16. data := `{"name":"小王子","age":18}`
  17. resp, err := http.Post(url, contentType, strings.NewReader(data))
  18. if err != nil {
  19. fmt.Printf("post failed, err:%v\n", err)
  20. return
  21. }
  22. defer resp.Body.Close()
  23. b, err := ioutil.ReadAll(resp.Body)
  24. if err != nil {
  25. fmt.Printf("get resp failed, err:%v\n", err)
  26. return
  27. }
  28. fmt.Println(string(b))
  29. }

(2) server.go

  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. )
  6. func main() {
  7. http.HandleFunc("/post", postHandler)
  8. _ = http.ListenAndServe("127.0.0.1:9090", nil)
  9. }
  10. func postHandler(w http.ResponseWriter, r *http.Request) {
  11. defer r.Body.Close()
  12. // 1. 请求类型是application/x-www-form-urlencoded时解析form数据
  13. r.ParseForm()
  14. fmt.Println(r.PostForm) // 打印form数据
  15. fmt.Println(r.PostForm.Get("name"), r.PostForm.Get("age"))
  16. // 2. 请求类型是application/json时从r.Body读取数据
  17. b, err := ioutil.ReadAll(r.Body)
  18. if err != nil {
  19. fmt.Printf("read request.Body failed, err:%v\n", err)
  20. return
  21. }
  22. fmt.Println(string(b))
  23. answer := `{"status": "ok"}`
  24. w.Write([]byte(answer))
  25. }