文章

Go 标准库学习:net/http

net/http

1
import "net/http"

http包提供了HTTP客户端与服务端的实现

服务端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("hello world"))
})

http.HandleFunc("/go", func(w http.ResponseWriter, r *http.Request) {
    defer r.Body.Close()
    bytes, err := io.ReadAll(r.Body)
    if err != nil {
        log.Fatal(err)
    }
    log.Println(string(bytes))
})

http.ListenAndServe(":8080", nil)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
func main () {

    var handler Myhandler
    //自定义配置服务端参数以及handler
	s := http.Server{
		Addr:           ":8080",
		Handler:        handler,
		WriteTimeout:   1 * time.Second,
		ReadTimeout:    1 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	log.Fatal(s.ListenAndServe())
}

type Myhandler int

func (m Myhandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("hello world1"))
}

客户端

GET

1
2
3
4
5
6
7
8
9
10
11
12
resp, err := http.Get("http://localhost:8080")
if err != nil {
    fmt.Printf("err: %v\n", err)
}

defer resp.Body.Close()

b, err := io.ReadAll(resp.Body)
if err != nil {
    fmt.Printf("err: %v\n", err)
}
fmt.Printf("b: %v\n", string(b))

POST

1
2
3
4
5
var buf bytes.Buffer

json.NewEncoder(&buf).Encode(struct{ Name string }{"jason"})

http.Post("http://localhost:8080/go", "application/json", &buf)

管理HTTP Header

1
2
3
4
5
6
7
8
9
10
11
12
13
14
client := http.Client{}

req, _ := http.NewRequest("GET", "http://localhost:8080/", nil)
req.Header.Add("AccessToken", "asdfsafasdfsf")

resp, _ := client.Do(req)

defer resp.Body.Close()

b, err := io.ReadAll(resp.Body)
if err != nil {
    fmt.Printf("err: %v\n", err)
}
fmt.Printf("b: %v\n", string(b))
本文由作者按照 CC BY 4.0 进行授权