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 一道python难题
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度