net/http包提供了HTTP客户端和服务端的实现
超文本传输协议(HTTP,HyperText Transfer Protocol)是互联网上应用最为广泛的一种网络传输协议
所有的WWW文件都必须遵守这个标准。设计HTTP最初的目的是为了提供一种发布和接收HTML页面的方法。
1.HTTP客户端
1.2GET请求
resp, err := http.Get("https://www.bilibili.com/")
if err != nil {
fmt.Printf("get failed,err:%v\n",err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Printf("read failed,err:%v\n",err)
return
}
fmt.Println(string(body))
1.3带参数的GET请求
关于GET请求的参数需要使用Go语言内置的net/url这个标准库来处理
import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
)
func main() {
apiUrl := "http://127.0.0.1:9000/get"
u, err := url.ParseRequestURI(apiUrl)
if err != nil {
fmt.Printf("parse failed,err:%v\n",err)
}
fmt.Printf("%T\n",u) //*url.URL
fmt.Println(u) //http://127.0.0.1:9000/get
data := url.Values{}
data.Set("name","cheng")
data.Set("age","18")
//encode := data.Encode()
//fmt.Println(encode) //age=18&name=cheng
u.RawQuery = data.Encode()
fmt.Println(u) //http://127.0.0.1:9000/get
resp, err := http.Get(u.String())
if err != nil {
fmt.Printf("get failed,err:%v",err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Printf("get failed,err:%v",err)
return
}
fmt.Println(string(body))
}
对应的Server端HandlerFunc
func getHandler(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
data := r.URL.Query()
fmt.Println(data.Get("name"))
fmt.Println(data.Get("age"))
answer := `{"status": "ok"}`
w.Write([]byte(answer))
}
2.Post请求
url := "http://127.0.0.1:9090/post"
contentType := "application/json"
data := `{name:"cheng",age:"18"}`
resp, err := http.Post(url, contentType, strings.NewReader(data))
if err != nil {
fmt.Printf("post failed,err:%v\n",err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Printf("get failed,err:%v\n",err)
return
}
fmt.Println(string(body))
url := "http://www.bilibili.com/"
contentType := "application/json"
data := ``
resp, err := http.Post(url, contentType, strings.NewReader(da
if err != nil {
fmt.Printf("post failed,err:%v\n",err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Printf("get failed,err:%v\n",err)
return
}
fmt.Println(string(body))
对应的Server端HandlerFunc
func postHandler(w http.ResponseWriter, r *http.Request){
defer r.Body.Close()
r.ParseForm()
fmt.Println(r.PostForm) //打印form数据
fmt.Println(r.PostForm.Get("name"),r.PostForm.Get("age"))
body, err := ioutil.ReadAll(r.Body)
if err != nil {
fmt.Printf("read failed,err:%v",err)
return
}
fmt.Println(string(body))
answer := `{"status":"ok"}`
w.Write([]byte(answer))
}
3.默认的Server
net/http包是对net包的进一步封装,专门用来处理HTTP协议的数据。
func sayHello(w http.ResponseWriter,r *http.Request) {
fmt.Fprint(w,"HelloWorld")
}
func main() {
http.HandleFunc("/",sayHello)
err := http.ListenAndServe(":9000", nil)
if err != nil {
fmt.Printf("http server failed,err:%v\n",err)
return
}
}