import "net/http"
HTTP服务端
http.HandleFunc("/", IndexHandler)
address := "127.0.0.1:8080"
fmt.Printf("server is run : http://%s\n", address)
err := http.ListenAndServe(address, nil)
if err != nil {
log.Fatalln(err.Error())
}
func IndexHandler(w http.ResponseWriter, r *http.Request) {
fmt.Printf("RequestURI: %s\n", r.RequestURI)
fmt.Printf("Method: %s\n", r.Method)
fmt.Printf("RemoteAddr: %s\n", r.RemoteAddr)
fmt.Printf("URLQuery: %v\n", r.URL.Query())
fmt.Printf("Form: %s\n", r.Form)
fmt.Printf("\n")
_, _ = w.Write([]byte("hello world"))
}
// Get Body
defer r.Body.Close()
buf := make([]byte, 1024)
for {
num, err := r.Body.Read(buf)
if err == io.EOF {
break
}
if err != nil {
break
}
buf = append(buf, buf[:num]...)
}
fmt.Printf("Body: %s\n", string(buf))
_, _ = w.Write([]byte("hello world"))
var respVo struct {
Code int
Msg string
Data interface{}
}
respVo.Code = 200
respVo.Msg = "success"
respVoJson,_ := json.Marshal(respVo)
_, _ = w.Write([]byte(respVoJson))
cookie := http.Cookie{
Name: "token",
Value: "xxx",
Path: r.RequestURI,
Domain: "127.0.0.1",
Expires: time.Now().AddDate(0, 0, 1), // 一天后过期
Unparsed: nil,
}
cookieString := cookie.String()
w.Header().Add("Cookie", cookieString)
w.Header().Set("token", "xxx")
HTTP客户端
resp, _ := http.Get("http://127.0.0.1:8080")
defer resp.Body.Close()
fmt.Printf("StatusCode: %d\n", resp.StatusCode)
var LoginReq struct {
Username string `json:"username"`
Password string `json:"password"`
}
LoginReq.Username = "admin"
LoginReq.Password = "123123"
LoginReqJson, _ := json.Marshal(LoginReq)
LoginReqReader := strings.NewReader(string(LoginReqJson))
resp, _ := http.Post("http://127.0.0.1:8080", "application/json", LoginReqReader)
fmt.Printf("StatusCode: %d\n", resp.StatusCode)
defer func(Body io.ReadCloser) {
_ = Body.Close()
}(resp.Body)
client := http.Client{
Transport: nil,
CheckRedirect: nil,
Jar: nil,
Timeout: 200 * time.Millisecond, // 200ms
}
reader := strings.NewReader("测试")
request, _ := http.NewRequest(http.MethodOptions, "http://127.0.0.1:8080", reader)
resp, err := client.Do(request)
if err != nil {
log.Fatalln(err.Error())
}
defer func(Body io.ReadCloser) {
_ = Body.Close()
}(resp.Body)
fmt.Printf("%d\n", resp.StatusCode)
客户端请求可以保持
Session
和Cookie
buf := make([]byte, 1024)
for {
n, err := resp.Body.Read(buf)
if err == io.EOF {
break
}
if err != nil {
fmt.Printf("err : %s\n", err.Error())
break
}
buf = append(buf, buf[:n]...)
}
fmt.Printf("respBody: %s\n", string(buf))