Go语言基础之net/http
Go语言内置的net/http包十分的优秀,提供了HTTP客户端和服务端的实现。
func main() {
//路径处理
http.HandleFunc("/study",f1)
//ip地址和端口
http.ListenAndServe("127.0.0.1:9999",nil)
}
func f1(w http.ResponseWriter,r *http.Request) {
str := `<h1 style="color:red">你好啊,中国!</h1>`
w.Write([]byte(str))
}
启动项目后,浏览器访问:127.0.0.1:9999/study,就可以看到效果
HTTP客户端
GET请求示例
func main() {
res, err := http.Get("https://www.baidu.com/")
if err != nil {
fmt.Printf("get failed, err:%v\n", err)
return
}
//关流
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Printf("read failed, err:%v\n", err)
return
}
fmt.Print(string(body))
}
带参数的GET请求示例
需要使用Go语言内置的net/url这个标准库来处理。
server端
func main() {
//路径处理
http.HandleFunc("/get",getHandler)
//ip地址和端口
http.ListenAndServe("127.0.0.1:9999",nil)
}
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))
}
client端:
var (
//用全局的client对象,防止短时间建立多次连接,消耗资源
client = http.Client{
Transport: &http.Transport{
DisableKeepAlives: false,
},
}
)
func main() {
apiUrl := "http://127.0.0.1:9999/get/"
data := url.Values{}
data.Set("name","张三")
data.Set("age","12")
ur, err := url.Parse(apiUrl)
ur.RawQuery = data.Encode()
if err != nil {
fmt.Printf("parse fail,err :%v\n",err)
}
//这里可以用第二种方法
//resp, err := http.Get(ur.String())
request, err := http.NewRequest("GET", ur.String(), nil)
if err != nil {
fmt.Printf("request fail,err :%v\n",err)
return
}
//http.DefaultClient.Do(request)也可以用这种的,但是会每次都建立一个连接
//用默认的client,复用client
resp, err := client.Do(request)
all, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Printf("read body fail,err :%v\n",err)
return
}
//必须要关
defer resp.Body.Close()
fmt.Println(string(all))
}
返回结果:
{"status": "ok"}
Post请求
server端:
func main() {
//路径处理
http.HandleFunc("/post",postHandler)
//ip地址和端口
http.ListenAndServe("127.0.0.1:9999",nil)
}
func postHandler(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
// 1. 请求类型是application/x-www-form-urlencoded时解析form数据
r.ParseForm()
fmt.Println(r.PostForm) // 打印form数据
fmt.Println(r.PostForm.Get("name"), r.PostForm.Get("age"))
// 2. 请求类型是application/json时从r.Body读取数据
b, err := ioutil.ReadAll(r.Body)
if err != nil {
fmt.Printf("read request.Body failed, err:%v\n", err)
return
}
fmt.Println(string(b))
answer := `{"status": "ok"}`
w.Write([]byte(answer))
}
client端:
func main() {
apiUrl := "http://127.0.0.1:9999/post"
contentType := "application/json"
data := `{"name":"小王子","age":18}`
resp, err := http.Post(apiUrl, contentType, strings.NewReader(data))
if err != nil {
fmt.Printf("post fail,err :%v\n",err)
}
defer resp.Body.Close()
all, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Printf("read body fail,err :%v\n",err)
return
}
fmt.Println(string(all))
}
返回结果:
{"status": "ok"}