DEV Community

Cover image for Go programming API's and How I handle CORS.
Peter B
Peter B

Posted on

Go programming API's and How I handle CORS.

The best way to learn is to teach so Here I go.

We are going to write a simple Go Web API

Have You tried to create a web service or API before ?

If Your answer is Yes then You have experienced this issue before.
If You are creating one(API or webservice) for the first time then You are going to face the same issue so I am here to show what helped My project.

First of all what is CORS(Cross-Origin Resource Sharing)?.

The answer to that is a very long one.
Let us just called it that thing that has You wondering why Your project works fine on Your local machine but fails to work in the browser when You upload Your project online.

Confused Yet?

Let us write our web server first.
We are going to use a go package called gin or gin-gonic.

So We create a folder for our project in terminal
mkdir mycoolapp
and start creating our files.
cd mycoolapp
run go mod
go mod init mycoolapp
install gin package from terminal.
go get -u github.com/gin-gonic/gin
now We edit file main.go in Your favourite code editor.
Here is how My program looks like

package main
//import gin package and fmt package
import (
       "fmt"
       "github.com/gin-gonic/gin"
)
func main() {   
       fmt.Println("My API Server")
       router := gin.Default()  
       router.Run(":9000") 



}

Enter fullscreen mode Exit fullscreen mode

In the program above We import the packages fmt and gin
In the main function We set up gin with defaults and listen on port 9000.

You can now run that program with command.
go run main.go

The server should be able to run but it cannot return anything to clients.
We handle this by creating a handler.
Code below.

package main

//import gin package and fmt package
import (
    "fmt"

    "github.com/gin-gonic/gin"
)

//our handler
func simpleHandler(c *gin.Context) {
    c.JSON(200, gin.H{
        "message": "nice service",
    })
}

func main() {
    fmt.Println("My news Api Server")
    router := gin.Default()
    router.GET("/hello", simpleHandler) //our route with handler
    router.Run(":9000")

}
Enter fullscreen mode Exit fullscreen mode

We have added the function simpleHandler to handle GET requests to endpoint at /hello.

Our handler simply returns a json response.
This works fine for command line apps.
This can fail if You start creating front end clients that work using browsers.
Then such errors come up

has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

Example CORS Errors

Luckily there is a workaround if You run into such issues.
The package
"github.com/gin-contrib/cors"
solves this issue easily.
We install it by running
go get "github.com/gin-contrib/cors"

Let us update our main.go file.

package main

//import gin package and fmt package
import (
    "fmt"

    "github.com/gin-contrib/cors" //import cors package
    "github.com/gin-gonic/gin"
)

//our handler
func simpleHandler(c *gin.Context) {
    c.JSON(200, gin.H{
        "message": "nice service",
    })
}

func main() {
    fmt.Println("My news Api Server")
    router := gin.Default()
    config := cors.Default() //set up default cors config
    router.Use(config)  //use cors with our router
    router.GET("/hello", simpleHandler) //our route with handler
    router.Run(":9000")

}
Enter fullscreen mode Exit fullscreen mode

We have updated our file by importing the
github.com/gin-contrib/cors
package.
Set it up with defaults
config := cors.Default()
and then used it with our router
router.Use(config).
No more CORS errors in the browser.
Enjoy.

Next post will be about creating a News API/Web service.

Top comments (0)