Home >Backend Development >Golang >How to Set HTTP Headers in a Go Web Server using gorilla/mux?

How to Set HTTP Headers in a Go Web Server using gorilla/mux?

DDD
DDDOriginal
2024-12-23 02:05:08868browse

How to Set HTTP Headers in a Go Web Server using gorilla/mux?

Setting HTTP Headers in Go Web Server

When developing a web server using Go, it is often necessary to set HTTP headers in response to client requests. This allows you to control browser behavior and provide essential information about the server and its resources.

To set HTTP headers in a Go web server using gorilla/mux and net/http, you can use the Set() method of the Header() function. Here's an example of how to set the Access-Control-Allow-Origin header to "*":

func saveHandler(w http.ResponseWriter, r *http.Request) {
    // allow cross domain AJAX requests
    w.Header().Set("Access-Control-Allow-Origin", "*")
}

By adding the above lines to your handler function, you instruct the server to respond to cross-origin requests from any origin with the Access-Control-Allow-Origin header set to "*". This enables cross-domain AJAX calls without being blocked by the same-origin policy.

To make this header available for all your routes, you can use gorilla/mux's Use() function to add a middleware to your router:

func main() {
    r := mux.NewRouter()
    r.Use(mux.CORSMethodMiddleware(r))
    r.HandleFunc("/save", saveHandler)
    http.Handle("/", r)
    http.ListenAndServe(":"+port, nil)
}

This middleware will automatically add the Access-Control-Allow-Origin header to all responses, regardless of the route.

The above is the detailed content of How to Set HTTP Headers in a Go Web Server using gorilla/mux?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn