Go: enabling CORS

Go: enabling CORS

In this article, we'll walk you through the steps required to enable CORS on your Go server, allowing requests from any source.

CORS, which stands for Cross-Origin Resource Sharing, is a web browser security policy that restricts requests for resources from different origins. This measure is intended to protect users from potential security threats, but it can also create restrictions when developing web applications that need to interact with different sources. Fortunately, it is possible to implement CORS in your Go server to allow requests from different domains while ensuring the security of your resources.

In this article, well walk you through the steps required to enable CORS on your Go server, allowing requests from any source. Before proceeding, make sure you have Go installed on your system.

As mentioned above, CORS is a web browser security policy that restricts requests for resources from sources other than the origin of the website making the request. The source consists of the protocol (http or https), the domain and the port.

An example of a different origin request would be a web page hosted at https://a.tld attempting to make a request to a server at `https://b.tld. Without a proper CORS policy, the browser will block this request.

To enable CORS on your Go server, you need to modify the server response headers to include the appropriate CORS headers.

To get started, create a new directory for your Go project and initialize a new Go module in it:

mkdir mio-progetto-go
cd mio-progetto-go
go mod init mio-progetto-go

Now lets create our main.go e importiamo il pacchetto to create the HTTP server:

package main

import (
    "fmt"
    "net/http"
)

Next, we define a handler for requests to our server. This handler will be responsible for adding CORS headers to all incoming requests. Add the following code to your `main.go file:

func handleRequest(w http.ResponseWriter, r *http.Request) {
    // Aggiungi le intestazioni CORS
    w.Header().Set("Access-Control-Allow-Origin", "*")
    w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
    w.Header().Set("Access-Control-Allow-Headers", "Content-Type")

    // Gestisci le richieste OPTIONS inviate dai browser per verificare le politiche CORS
    if r.Method == "OPTIONS" {
        return
    }

    // Il tuo codice per gestire le altre richieste va qui...

    // Esempio di risposta
    fmt.Fprintf(w, "Benvenuto nel mio server Go!")
}

func main() {
    // Imposta il gestore per le richieste sul percorso "/"
    http.HandleFunc("/", handleRequest)

    // Avvia il server sulla porta 8080
    fmt.Println("Server in ascolto sulla porta 8080...")
    http.ListenAndServe(":8080", nil)
}

You can now start the Go server with the following command:

go run main.go

Your Go server is now listening on port 8080 and will allow requests from any source thanks to the CORS headers we set up.