How can you enable CORS on your Go Web Application ?
2 min readNov 22, 2023
This article assumes you knew already what is CORS and how it works and you just wish to enable it on your web server.
Enabling CORS (Cross-Origin Resource Sharing) in a GoLang server involves setting the appropriate headers to allow or restrict cross-origin requests. Here’s a basic example using the net/http
package:
package main
import (
"net/http"
)
func enableCors(w *http.ResponseWriter) {
(*w).Header().Set("Access-Control-Allow-Origin", "*")
(*w).Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE")
(*w).Header().Set("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With")
}
func handleRequest(w http.ResponseWriter, r *http.Request) {
enableCors(&w)
// Your handler logic goes here
// Example: Writing a response
w.Write([]byte("Hello, CORS!"))
}
func main() {
http.HandleFunc("/", handleRequest)
http.ListenAndServe(":8080", nil)
}
In this example:
- The
enableCors
function sets the necessary CORS headers. - The
handleRequest
function is the handler for your routes. Make sure to callenableCors
at the beginning of this function. - You can replace the example logic in
handleRequest
with your own application logic.