server端:
package main
import (
"fmt"
"io"
"net/http"
)
func main() {
//注册路由 func是回调函数,用于路由的响应,
http.HandleFunc("/user", func(writer http.ResponseWriter, request *http.Request) {
//request:包含客户端发来的数据
fmt.Println("客户请求:",request)
//write:通过write将数据返回给客户端
_, _ = io.WriteString(writer, "这是/user返回的数据")
})
//请求指定路由,返回指定结果
http.HandleFunc("/name", func(writer http.ResponseWriter, request *http.Request) {
_, _ = io.WriteString(writer, "这是/name返回的数据")
})
//请求指定路由,返回指定结果
http.HandleFunc("/id", func(writer http.ResponseWriter, request *http.Request) {
_, _ = io.WriteString(writer, "这是/id返回的数据")
})
fmt.Println("http start")
if err := http.ListenAndServe("localhost:8088", nil);err != nil {
fmt.Println("启动服务失败",err)
return
}
}
client端:
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
//http包
client := http.Client{}
//func (c *Client) Get(url string) (resp *Response, err error)
//get到需要测试的url
resp, err := client.Get("https://www.baidu.com")
if err != nil {
fmt.Println("请求失败",err)
return
}
//get到header的指定key
ct := resp.Header.Get("Content-Type")
date := resp.Header.Get("Date")
sr := resp.Header.Get("Server")
//输出打印结果
fmt.Println(ct,date,sr)
//获取请求的url,状态码,状态
url := resp.Request.URL
code := resp.StatusCode
status := resp.Status
//输出打印结果
fmt.Println(url,code,status)
//拿到Body体内的所有内容
body := resp.Body
//输出打印body
fmt.Println(body)
//接收body转换为string类型
readAll, err := ioutil.ReadAll(body)
if err != nil {
fmt.Println("请求body失败",err)
return
}
//输出结果
fmt.Println(string(readAll))
}
先启动server在启动client