基本的な使い方
HTTP クライアント。デフォルトで Http.DefaultClient を使用します。
1. Getリクエストを送信する
resp, err := http.Get("https://jsonplaceholder.typicode.com/posts/1")
if err != nil {
panic(err)
}
defer resp.Body.Close()
2. jsonデータを使用して投稿リクエストを送信します
//模拟json串
data := map[string]interface{
}{
"name": "kd",
"age": 18,
}
b, _ := json.Marshal(data)
r:= bytes.NewReader(b)
resp, err := http.Post("http://www.atool.org/httptest.php", "application/json", r)
if err != nil {
panic(err)
}
defer resp.Body.Close()
3. クライアントとリクエストリクエストをカスタマイズする
クライアントのタイムアウトを 3 秒に設定します
c := &http.Client{
Timeout: time.Second * 3}
resp, _ := c.Get("http://www.atool.org/httptest.php")
//定制请求:可以通过NewRequest方法实现发送put、delete请求等
request, err := http.NewRequest("put", "http://www.atool.org/httptest.php", nil)
if err != nil {
panic(err)
}
resp, err := c.Do(request)
HTTPサーバー
ServeMux は HTTP リクエスト マルチプレクサー (HTTP リクエスト マルチプレクサー) です。
1. Http.DefaultServeMux を使用する
type CustomeHandle struct {
}
func (*CustomeHandle) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("helloworld"))
}
//1.使用Handle,需实现ServerHTTP接口
http.Handle("/", &CustomeHandle{
})
//2.使用Handlefunc,匿名函数
http.HandleFunc("/a", func(writer http.ResponseWriter, request *http.Request) {
w.Write([]byte("helloworld"))
})
http.ListenAndServe(":8080", nil)
2. カスタマイズされたHTTPサーバー
読み取りタイムアウトと書き込みタイムアウトを 1 秒に設定します。
server := http.Server{
ReadTimeout: time.Second,
WriteTimeout: time.Second,
Addr: "127.0.0.1:8080",
}
mux:=http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello"))
})
server.ListenAndServe()