dongqianzong4275 2014-07-30 03:46
浏览 1883
已采纳

如何设置多值HTTP标头,例如Content-Security-Policy?

I'm trying to set the Content-Security-Policy header on a http.ResponseWriter object. This is a header with multiple values. My problem is that all the methods for http.Header take a single key and a single value. For example, the Set() method looks like this:

func (h Header) Set(key, value string)

There's no method for assigning a slice of values to a header field. I want a header that looks like this.

header := http.Header{
    "Content-Type": {"text/html; charset=UTF-8"},
    "Content-Security-Policy": {"default-src 'self'", "font-src themes.googleusercontent.com", "frame-src 'none'", "style-src 'self' fonts.googleapis.com"},
}

This will create the header, but I don't know how to associate it with the http.ResponseWriter object. Furthermore, if I were somehow able to replace the ResponseWriter's header with the header above, would I have to set the Content-Length field by hand?

  • 写回答

3条回答 默认 最新

  • douju1852 2014-07-30 03:58
    关注

    I'm not sure I fully understand the problem, however Content-Security-Policy expects one header that contains a list separated by ;.

    If you want to use a slice you can always use something like this:

    csp := []string{"default-src: 'self'", "font-src: 'fonts.googleapis.com'", "frame-src: 'none'"}
    header := http.Header{
        "Content-Type": {"text/html; charset=UTF-8"},
    }
    header.Set("Content-Security-Policy", strings.Join(csp, "; "))
    

    Also if you want to send the header multiple times with different values (like you originally intended, I think), you can use header.Add.

    Add adds the key, value pair to the header. It appends to any existing values associated with key.

    If you want to use that in your http handler, get the header with ResponseWriter.Header():

    func Handler(rw http.ResponseWriter, req *http.Request) {
        header := rw.Header()
        csp := []string{"default-src: 'self'", "font-src: 'fonts.googleapis.com'", "frame-src: 'none'"}
    
        header.Set("Content-Type": "text/html; charset=UTF-8")
        header.Set("Content-Security-Policy", strings.Join(csp, "; "))
        rw.WriteHeader(200) //or write anything really
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器