1. import "net/http"

HTTP服务端

  1. http.HandleFunc("/", IndexHandler)
  1. address := "127.0.0.1:8080"
  2. fmt.Printf("server is run : http://%s\n", address)
  3. err := http.ListenAndServe(address, nil)
  4. if err != nil {
  5. log.Fatalln(err.Error())
  6. }
  1. func IndexHandler(w http.ResponseWriter, r *http.Request) {
  2. fmt.Printf("RequestURI: %s\n", r.RequestURI)
  3. fmt.Printf("Method: %s\n", r.Method)
  4. fmt.Printf("RemoteAddr: %s\n", r.RemoteAddr)
  5. fmt.Printf("URLQuery: %v\n", r.URL.Query())
  6. fmt.Printf("Form: %s\n", r.Form)
  7. fmt.Printf("\n")
  8. _, _ = w.Write([]byte("hello world"))
  9. }
  1. // Get Body
  2. defer r.Body.Close()
  3. buf := make([]byte, 1024)
  4. for {
  5. num, err := r.Body.Read(buf)
  6. if err == io.EOF {
  7. break
  8. }
  9. if err != nil {
  10. break
  11. }
  12. buf = append(buf, buf[:num]...)
  13. }
  14. fmt.Printf("Body: %s\n", string(buf))
  1. _, _ = w.Write([]byte("hello world"))
  1. var respVo struct {
  2. Code int
  3. Msg string
  4. Data interface{}
  5. }
  6. respVo.Code = 200
  7. respVo.Msg = "success"
  8. respVoJson,_ := json.Marshal(respVo)
  9. _, _ = w.Write([]byte(respVoJson))
  1. cookie := http.Cookie{
  2. Name: "token",
  3. Value: "xxx",
  4. Path: r.RequestURI,
  5. Domain: "127.0.0.1",
  6. Expires: time.Now().AddDate(0, 0, 1), // 一天后过期
  7. Unparsed: nil,
  8. }
  9. cookieString := cookie.String()
  10. w.Header().Add("Cookie", cookieString)
  1. w.Header().Set("token", "xxx")

HTTP客户端

  1. resp, _ := http.Get("http://127.0.0.1:8080")
  2. defer resp.Body.Close()
  3. fmt.Printf("StatusCode: %d\n", resp.StatusCode)
  1. var LoginReq struct {
  2. Username string `json:"username"`
  3. Password string `json:"password"`
  4. }
  5. LoginReq.Username = "admin"
  6. LoginReq.Password = "123123"
  7. LoginReqJson, _ := json.Marshal(LoginReq)
  8. LoginReqReader := strings.NewReader(string(LoginReqJson))
  9. resp, _ := http.Post("http://127.0.0.1:8080", "application/json", LoginReqReader)
  10. fmt.Printf("StatusCode: %d\n", resp.StatusCode)
  11. defer func(Body io.ReadCloser) {
  12. _ = Body.Close()
  13. }(resp.Body)
  1. client := http.Client{
  2. Transport: nil,
  3. CheckRedirect: nil,
  4. Jar: nil,
  5. Timeout: 200 * time.Millisecond, // 200ms
  6. }
  7. reader := strings.NewReader("测试")
  8. request, _ := http.NewRequest(http.MethodOptions, "http://127.0.0.1:8080", reader)
  9. resp, err := client.Do(request)
  10. if err != nil {
  11. log.Fatalln(err.Error())
  12. }
  13. defer func(Body io.ReadCloser) {
  14. _ = Body.Close()
  15. }(resp.Body)
  16. fmt.Printf("%d\n", resp.StatusCode)

客户端请求可以保持SessionCookie

  1. buf := make([]byte, 1024)
  2. for {
  3. n, err := resp.Body.Read(buf)
  4. if err == io.EOF {
  5. break
  6. }
  7. if err != nil {
  8. fmt.Printf("err : %s\n", err.Error())
  9. break
  10. }
  11. buf = append(buf, buf[:n]...)
  12. }
  13. fmt.Printf("respBody: %s\n", string(buf))