基本使用
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.发送post请求,携带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.定制客户端与request请求
设定客户端的超时时间为3s
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 Request multiplexer)
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服务器
设置读超时、写超时都为1s
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()