设置 HTTP 标头 [英] Setting HTTP headers
问题描述
我正在尝试在我的 Go 网络服务器中设置一个标头.我正在使用 gorilla/mux
和 net/http
包.
I'm trying to set a header in my Go web server. I'm using gorilla/mux
and net/http
packages.
我想设置 Access-Control-Allow-Origin: *
以允许跨域 AJAX.
I'd like to set Access-Control-Allow-Origin: *
to allow cross domain AJAX.
这是我的 Go 代码:
Here's my Go code:
func saveHandler(w http.ResponseWriter, r *http.Request) {
// do some stuff with the request data
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/save", saveHandler)
http.Handle("/", r)
http.ListenAndServe(":"+port, nil)
}
net/http
包中有描述发送 http 请求标头的文档,就好像它是客户端一样 - 我不确定如何设置响应标头?
The net/http
package has documentation describing sending http request headers as if it were a client - I'm not exactly sure how to set response headers?
推荐答案
没关系,我想通了 - 我在 Header()
上使用了 Set()
方法(哦!)
Never mind, I figured it out - I used the Set()
method on Header()
(doh!)
我的处理程序现在看起来像这样:
My handler looks like this now:
func saveHandler(w http.ResponseWriter, r *http.Request) {
// allow cross domain AJAX requests
w.Header().Set("Access-Control-Allow-Origin", "*")
}
也许这会在某个时候帮助像我这样缺乏咖啡因的人:)
Maybe this will help someone as caffeine deprived as myself sometime :)
这篇关于设置 HTTP 标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!