设置HTTP标头 [英] Setting HTTP headers
问题描述
我正在尝试在Go Web服务器中设置标题。我正在使用 gorilla / mux
和 net / http
包。
我想设置 Access-Control-Allow-Origin:*
以允许跨域AJAX。
这是我的Go代码:
func saveHandler(w http.ResponseWriter,r * http.Request){
//用请求数据做一些事情
$ b $ func main(){
r:= mux.NewRouter()
r.HandleFunc(/ save ,saveHandler)
http.Handle(/,r)
http.ListenAndServe(:+ port,nil)
}
$ b net / http
包有文档描述发送http请求标题,就好像它是客户端一样 - 我不确定如何设置响应头文件?
没关系,我想通了 - 我用<$在 Header()
(doh!)中加入c $ c> Set()方法
我的处理程序看起来像这样:
func saveHandler(w http.Response Writer,r * http.Request){
//允许跨域AJAX请求
w.Header()。Set(Access-Control-Allow-Origin,*)
}
也许这可以帮助某人在某段时间被剥夺咖啡因:)
I'm trying to set a header in my Go web server. I'm using gorilla/mux
and net/http
packages.
I'd like to set Access-Control-Allow-Origin: *
to allow cross domain AJAX.
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)
}
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?
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屋!