dream02008 2019-01-02 10:46
浏览 81
已采纳

从文件读取HTTP标头的最有效方法?

I'm looking for an efficient way to read HTTP headers from a textfile to be later sent with an HTTP request. Consider the following code (which currently contains basic net/http request functionality):

func MakeRequest(target string, method string) {
client := &http.Client{}
req, _ := http.NewRequest(method, target, nil)

//Headers manually..
req.Header.Add("If-None-Match", `some value`)

response, _ := client.Do(req)
body, _ := ioutil.ReadAll(response.Body)
fmt.Println(string(body))
}

I started by using ioutil.ReadFile like this:

func main() {
data, _ := ioutil.ReadFile("/opt/tests/req.txt")
fmt.Print(string(data))
}

But taking this text, splitting it by some indicator (lets say ":") and then placing the information in req.Header.Add("var1", "var2") per-header seems like an over-kill.

Question: Any better way to send HTTP requests with headers from a text file in go?

  • 写回答

2条回答 默认 最新

  • doudu3961 2019-01-02 14:44
    关注

    If you only want some headers defined, another option is to define the headers in a Json file and apply the following code (file reading not included):

    var jsonMap map[string]string
    err = json.Unmarshal(jsonBytesFromFile, &jsonMap)
    if err != nil {
        log.Fatal("unable to parse json: ", err)
    }
    
    for k, v := range jsonMap {
        log.Printf("setting Header : %s : %s", k, v)
        responseWriter.Header().Add(k, v) // you may prefer Set()
    }
    

    The json looks like this:

    { 
        "Content-type": "text/plain",
        "Cache-Control": "only-if-cached"
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 爬取1-112页所有帖子的标题但是12页后要登录后才能 我使用selenium模拟登录 账号密码输入后 会报错 不知道怎么弄了
  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点