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

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

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

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

1
2
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 @   许伟强  阅读(681)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示