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

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

Linda Hamilton
Release: 2024-12-21 13:16:10
Original
235 people have browsed it

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

Setting Headers in a Go HTTP Server

When developing web APIs, it's often necessary to set HTTP headers on response objects to control the behavior of the browser. In Go, using gorilla/mux and net/http to build a web server, setting response headers is a straightforward process.

Consider this example, which aims to allow cross-domain AJAX requests by setting the "Access-Control-Allow-Origin" header to "*":

package main

import (
    "net/http"
    "github.com/gorilla/mux"
)

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

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

The key to setting response headers is the Header() method on the ResponseWriter object:

  • w.Header().Set(): Sets the header to the specified value.

In this case, the code uses w.Header().Set("Access-Control-Allow-Origin", "*") to add the desired header and value. The result will be an HTTP response with the "Access-Control-Allow-Origin" header set to "*".

This simple method allows you to control the HTTP headers sent with your server's responses, enabling features such as Cross-Origin Resource Sharing (CORS).

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template