Home > Backend Development > Golang > How Do I Set HTTP Headers in Go?

How Do I Set HTTP Headers in Go?

Barbara Streisand
Release: 2024-12-26 18:56:22
Original
114 people have browsed it

How Do I Set HTTP Headers in Go?

Setting HTTP Headers in Go

When developing a web server in Go, occasionally it may become necessary to set HTTP headers on requests. This is where the gorilla/mux and net/http libraries prove useful.

Setting Response Headers

To set an HTTP header on a response, simply use the Set() method of the Header() method on the ResponseWriter:

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

Example Usage

In this example, we set the "Access-Control-Allow-Origin" header to "*", allowing cross-domain AJAX requests.

Gotchas

Ensure your saveHandler function includes the necessary import at the top:

import (
    "net/http"
)
Copy after login

The above is the detailed content of How Do I Set HTTP Headers in Go?. 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