dream02008 2019-01-02 02: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 06: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部