Golang使用http发送请求遇到的一个坑

尝试发送的请求的 header 的 Host 字段

request, err := http.NewRequest("GET", url, nil)
request.Header.Set("Host","example.com")

这样写一直都是错误的 ,在 Request.header 有一句

For incoming requests, the Host header is promoted to the
Request.Host field and removed from the Header map.

翻译就是

对于传入的请求,Host 标头被提升为
Request.Host 字段并从 Header 映射中移除。

必须要这样写

request.Host = "example.com"

 

附一个简单的调用:

package testapisix

import (
    "io/ioutil"
    "log"
    "net/http"
    "testing"
)

func Test_GET(t *testing.T){
    url := "http://127.0.0.1:9080/"
    request, e := http.NewRequest("GET", url, nil)
    if e != nil {
        t.Fatal(e)
    }
    request.Host = "example.com"
    client := &http.Client{}
    response, e := client.Do(request)
    if e != nil {
        t.Fatal(e)
    }
    defer response.Body.Close()
    log.Println(response.Header)
    body, _ := ioutil.ReadAll(response.Body)
    //读取body
    log.Println(string(body))
}

func Test_POST(t *testing.T){
    url := "http://127.0.0.1:9080/"
    request, e := http.NewRequest("POST", url, nil)
    if e != nil {
        t.Fatal(e)
    }
    request.Host = "example.com"
    csrfToken := "xxx"
    request.Header.Add("token",csrfToken)
    cc := new(http.Cookie)
    cc.Name = "token"
    cc.Value = csrfToken
    request.AddCookie(cc)
    client := &http.Client{}
    response, e := client.Do(request)
    if e != nil {
        t.Fatal(e)
    }
    defer response.Body.Close()
    log.Println(response.Header)
    body, _ := ioutil.ReadAll(response.Body)
    //读取body
    log.Println(string(body))
}

apisix 开启 csrf token

http://127.0.0.1:9080/apisix/admin/routes/1

POST

header.X-API-KEY 


{
  "methods": ["GET","POST"],
  "host": "example.com",
  "uri": "/*",
  "plugins": {
    "csrf": {
      "name":"token",
      "key": "unique_key"
    }
  },
  "upstream": {
    "type": "roundrobin",
    "nodes": {
      "web1:80": 1
    }
  }
}

 

 HTTP client 連接池 https://www.cnblogs.com/paulwhw/p/15972645.html

HTTP body close 與内存泄漏

server

package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
)

func main() {
    http.Handle("/get", new(Handler))
    //端口号
    http.ListenAndServe(":2112", nil)
}

type Handler struct {
}

func (m *Handler) ServeHTTP(r http.ResponseWriter, q *http.Request) {
    ccc, _ := ioutil.ReadAll(q.Body)
    fmt.Println(string(ccc))
    result := []byte("hello")
    _, e := r.Write(result)
    if e != nil {
        log.Fatal(e)
    }
}

client

package main

import (
    "bytes"
    "crypto/tls"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
)

func main() {
    var c = map[string]string{
        "name": "jack",
    }
    z, _ := json.Marshal(c)
    HttpPost(z)
}

// var a = `{"name":"jack"}`
func HttpPost(content []byte) {
    var j = bytes.NewBuffer(content)
    // io.Reader 需要一个 io.Reader 对象? 从字符串中获取怎么做 - strings.NewReader("name=cjb")
    tr := &http.Transport{
        TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
    }
    client := &http.Client{Transport: tr}
    //提交请求
    reqest, err := http.NewRequest("POST", "http://127.0.0.1:2112/get", j)
    if err != nil {
        panic(err)
    }
    //增加header选项
    reqest.Header.Add("Content-Type", "application/json")
    resp, err := client.Do(reqest)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        panic(err)
    }
    log.Println(string(body))
    fmt.Println("success")
}

 

 

data := url.Values{}
data.Set("name", "rnben")
var j = strings.NewReader(data.Encode())

与 postman 发送 x-www-form-urlencoded 一样 键值对

 

params := map[string]interface{}{
  "fromUserId": 1,
  "objectName": 2,
  "toGroupIds": 3
   "content":    4,
}
bParams, _ := json.Marshal(params)
strings.NewReader(string(bParams))

 

 

 

posted @ 2022-06-29 00:18  许伟强  阅读(628)  评论(0编辑  收藏  举报