How to Enable CORS in GoLang

Sheeraz Gul Feb 02, 2024
  1. GoLang CORS
  2. Enable CORS in GoLang
  3. CORS Package in GoLang
  4. Use the GET and POST Methods With CORS in Go
How to Enable CORS in GoLang

This tutorial demonstrates how to enable and use CORS in GoLang.

GoLang CORS

Cross-Origin Resource Sharing (CORS) is an HTTP header-based process that defines the origins from which the browsers are permitted to load and use resources. The CORS is used to relax the Same-origin policy policy, which permits JS scripts on a page to access data on other pages.

The same origin policy ensures that both web pages are of the same origin. This policy helps improve security by isolating malicious documents.

The CORS is used to relax the same origin policy by using the headers as shown in the table:

Header Type Description
Origin Request Used to indicate the request’s origin to the server.
Access-Control-Request-Method Request Used to indicate the HTTP methods to implement the request to the server.
Access-Control-Request-Headers Request Used to indicate the headers in the request to the server.
Access-Control-Allow-Origin Response Used for the origins that are allowed by the server.
Access-Control-Allow-Methods Response Used for the list of comma-separated methods allowed by the server.
Access-Control-Allow-Headers Response Used for the list of comma-separated headers allowed by the server.
Access-Control-Expose-Headers Response Used for the list of comma-separated headers allowing the client to access a response.
Access-Control-Max-Age Response Used to inform the server how many seconds it takes to cache the response to the pre-flight request.
Access-Control-Allow-Credentials Response Used to allow or restrict the Credentials for the server.

Enable CORS in GoLang

We can implement a function in Go where we implement our CORS policy by using the net/http package of GoLang. Follow the step-by-step process to enable the CORS in GO:

  • Create an application that runs on the localhost with a port number that includes headers that will access resources of the current server from other pages. See the headers:
    Response_Writer.Header().Set("Content-Type", "text/plain; charset=utf-8")
    Response_Writer.Header().Set("Access-Control-Allow-Origin", "http://127.0.1.1:5555")
    Response_Writer.Header().Set("Access-Control-Max-Age", "10")
    
  • As we can see, we enable our CORS policy, so the JS script from http://127.0.1.1:5555 can access data from our pages or resources. Better to keep these headers in a method so we can implement the CORS policy for our server.
  • Now set the CORS policy for our server; for example, the function for headers is DelftstackHandler. Now do this:
    http.HandleFunc("/delftstack", DelftstackHandler)
    log.Fatal(http.ListenAndServe(":3000", nil))
    

The log.Fatal(http.ListenAndServe(":3000", nil)) will set the CORS policy for our server. Let’s implement this example and see the output.

The GoLang file for CORS policy:

package main

import (
	"fmt"
	"log"
	"net/http"
)

func main() {

	http.HandleFunc("/delftstack", DelftstackHandler)

	log.Println("Listening the request..")
	log.Fatal(http.ListenAndServe(":3000", nil))
}

func DelftstackHandler(Response_Writer http.ResponseWriter, _ *http.Request) {

	Response_Writer.Header().Set("Content-Type", "text/plain; charset=utf-8")
	Response_Writer.Header().Set("Access-Control-Allow-Origin", "http://127.0.1.1:5555")
	Response_Writer.Header().Set("Access-Control-Max-Age", "10")
	fmt.Fprintf(Response_Writer, "Hello, this is delftstack.com!")
}

The HTML/JS file for response:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Delftstack</title>
</head>

<body>

    <script>
        async function doRequest() {
            let localhost_url = 'http://localhost:3000/delftstack';
            let page_response = await fetch(localhost_url);

            if (page_response.ok) {

                let text = await page_response.text();

                return text;
            } else {
                return `HTTP error: ${page_response.status}`;
            }
        }

        doRequest().then(data => {
            document.getElementById("print_output").innerText = data;
        });
    </script>

    <div id="print_output">

    </div>

</body>

</html>

The above code will write the response Hello, this is delftstack.com! from the Go code in the HTML/JS page.

See the output:

CORS Policy

CORS Package in GoLang

A third-party package CORS is used to implement the Cross-Origin Resource Sharing by defining the NET/HTTP handler. Before start using this package, we have to install it.

Use the following command:

go get github.com/rs/cors

Get CORS

Once it is successfully installed, we can use CORS in our code. Let’s try a simple example:

package main

import (
    "net/http"

    "github.com/rs/cors"
)

func main() {
    Demo_Mux := http.NewServeMux()
    Demo_Mux.HandleFunc("/", func(Response_Writer http.ResponseWriter, Req *http.Request) {
        Response_Writer.Header().Set("Content-Type", "application/json")
        Response_Writer.Write([]byte("{\"hello!\": \"This is delftstack.com\"}"))
    })

    DemoHandler := cors.Default().Handler(Demo_Mux)
    http.ListenAndServe(":3000", DemoHandler)
}

In the code above, the cors.Default() will set up a middleware with default options where all origins are accepted with simple methods like GET and POST.

See the output for the above code:

Simple CORS Output

Use the GET and POST Methods With CORS in Go

We can also use the GET and POST methods to send the request by CORS. We must assign them in the CORS using the AllowedMethods field.

Let’s see the example:

package main

import (
	"net/http"

	"github.com/rs/cors"
)

func main() {

	Demo_Mux := http.NewServeMux()

	Demo_CORS := cors.New(cors.Options{
		AllowedOrigins:   []string{"*"}, //all
		AllowedMethods:   []string{http.MethodPost, http.MethodGet},
		AllowedHeaders:   []string{"*"}, //all
		AllowCredentials: false,         //none
	})

	Demo_Mux.HandleFunc("/delftstack", func(Response_Writer http.ResponseWriter, r *http.Request) {
		Response_Writer.Header().Set("Content-Type", "application/json")
		Response_Writer.Write([]byte("{\"hello!\": \"This is delftstack.com\"}"))
	})

	Demo_Handler := Demo_CORS.Handler(Demo_Mux)
	http.ListenAndServe(":3000", Demo_Handler)
}

The code above will use the CORS package to implement the policy and enable the two methods, GET and POST, to send the request.

See the output:

CORS GET POST

Author: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook