JIYIK CN >

Current Location:Home > Learning > PROGRAM > Go >

Enabling CORS in GoLang

Author:JIYIK Last Updated:2025/04/15 Views:

This article describes how to enable and use CORS in GoLang.


Go language CORS

Cross-origin resource sharing (CORS) is a process based on HTTP headers that defines the origins from which browsers are allowed to load and use resources. CORS is used to relax the same-origin policy, allowing JS scripts on one page to access data on other pages.

The same-origin policy ensures that two web pages have the same origin. This policy helps improve security by isolating malicious documents.

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

Header type illustrate
Origin Request Used to indicate to the server the origin of the request.
Access-Control-Request-Method Request It is used to indicate the HTTP method used to implement the request to the server.
Access-Control-Request-Headers Request Used to indicate headers in requests to the server.
Access-Control-Allow-Origin Response Used for origins allowed by the server.
Access-Control-Allow-Methods Response Comma-separated list of methods allowed by the server.
Access-Control-Allow-Headers Response Comma-separated list of headers allowed by the server.
Access-Control-Expose-Headers Response A comma-separated list of headers that the client is allowed to access the response.
Access-Control-Max-Age Response Used to tell the server how many seconds to cache the response to a preflight request.
Access-Control-Allow-Credentials Response Used to allow or restrict credentials for the server.

Enabling CORS in GoLang

We can implement a function in Go to implement our CORS policy by using the Go language's net/http package. Follow the step-by-step process to enable CORS in GO

Create an application running on localhost with a port number that contains headers that will access current server resources from other pages. View 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 have enabled the CORS policy, so the JS script from http://127.0.1.1:5555 can access the data in our page or resource. It is better to save these headers in a method so that we can implement the CORS policy for our server.
  • Now let's set up the CORS policy for our server; for example, the function for headers is JiyikHandler. Now do this:
    http.HandleFunc("/Jiyik", JiyikHandler)
    log.Fatal(http.ListenAndServe(":3000", nil))
    

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

GoLang file for CORS policy:

package main

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

func main() {

    http.HandleFunc("/Jiyik", JiyikHandler)

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

func JiyikHandler(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 Jiyik.com!")
}

HTML/JS files for responses:

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

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

<body>

    <script>
        async function doRequest() {
            let localhost_url = 'http://localhost:3000/Jiyik';
            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 Jiyi.com! to the Go code in the HTML/JS page.

See the output:

CORS Policy


CORS package in Go

The third-party package CORS is used to implement cross-origin resource sharing by defining NET/HTTP handlers. Before we start using this package, we must install it.

Use the following command:

go get github.com/rs/cors

Get CORS

Once installed successfully, 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 Jiyik.com"}"))
    })

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

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

Check out the output of the above code:

Simple CORS Output


Using GET and POST methods with CORS in Go

We can also send requests through CORS using GET and POST methods. We have to assign them in CORS using the AllowedMethods field.

Let's look at an 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("/Jiyik", func(Response_Writer http.ResponseWriter, r *http.Request) {
        Response_Writer.Header().Set("Content-Type", "application/json")
        Response_Writer.Write([]byte("{"hello!": "This is Jiyik.com"}"))
    })

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

The above code will use the CORS package to implement the policy and enable both GET and POST methods to send requests.

See the output:

CORS GET POST

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Install GoLang using Brew

Publish Date:2025/04/15 Views:82 Category:Go

This article describes how to install GoLang using Brew on Linux or macOS. Install GoLang using Brew brew installs missing packages in Linux and macOS. It makes it easy to install GoLang on Linux or macOS. Follow the steps below to install

GoLang RWMutex Detailed Introduction

Publish Date:2025/04/15 Views:116 Category:Go

This article introduces how to use rwmutex in Go language. Go language RWMutex mutex is the abbreviation of mutual exclusion, which is used to keep track of which thread has accessed a variable at any time. Mutex is a data structure provide

Getting a string representation of a structure in Go

Publish Date:2025/04/15 Views:63 Category:Go

Go allows us to serialize data from structures using a variety of simple standard methods. Converting a structure to a string using String method in Go The GoLang package String helps implement simple functions to manipulate and edit UTF-8

Convert JSON to struct in Go

Publish Date:2025/04/15 Views:126 Category:Go

This article describes how to convert JSON to struct in GoLang . Convert JSON to Struct using Unmarshal method in Go The encoding/json package of the Go language provides a function Unmarshal to convert JSON data into byte format. This func

Golang 中的零值 Nil

Publish Date:2023/04/27 Views:185 Category:Go

本篇文章介绍 nil 在 Golang 中的含义,nil 是 Go 编程语言中的零值,是众所周知且重要的预定义标识符。

Golang 中的 Lambda 表达式

Publish Date:2023/04/27 Views:699 Category:Go

本篇文章介绍如何在 Golang 中创建 lambda 表达式。Lambda 表达式似乎不存在于 Golang 中。 函数文字、lambda 函数或闭包是匿名函数的另一个名称。

Go 中的深度复制

Publish Date:2023/04/27 Views:136 Category:Go

当我们尝试生成对象的副本时,深层副本会准确复制原始对象的所有字段。 此外,如果它有任何对象作为字段,也会制作这些对象的副本。本篇文章介绍如何在 Golang 中进行深度复制。

在 Go 中捕获 Panics

Publish Date:2023/04/27 Views:104 Category:Go

像错误一样,Panic 发生在运行时。 换句话说,当您的 Go 程序中出现意外情况导致执行终止时,就会发生 Panics。让我们看一些例子来捕捉 Golang 中的Panics。

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial