<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Peter B</title>
    <description>The latest articles on Forem by Peter B (@pbelx).</description>
    <link>https://forem.com/pbelx</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F238806%2F124660cf-8bdb-4a98-a4f0-fff39a8114bc.png</url>
      <title>Forem: Peter B</title>
      <link>https://forem.com/pbelx</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/pbelx"/>
    <language>en</language>
    <item>
      <title>Go programming API's and How I handle CORS.</title>
      <dc:creator>Peter B</dc:creator>
      <pubDate>Sun, 10 Jul 2022 21:05:31 +0000</pubDate>
      <link>https://forem.com/pbelx/go-programming-apis-and-how-i-handle-cors-4fk4</link>
      <guid>https://forem.com/pbelx/go-programming-apis-and-how-i-handle-cors-4fk4</guid>
      <description>&lt;h4&gt;
  
  
  The best way to learn is to teach so Here I go.
&lt;/h4&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;We are going to write a simple Go Web API&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Have You tried to create a web service or API before ?&lt;/p&gt;

&lt;p&gt;If Your answer is Yes then You have experienced this issue before.&lt;br&gt;
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.&lt;/p&gt;
&lt;h2&gt;
  
  
  First of all what is CORS(Cross-Origin Resource Sharing)?.
&lt;/h2&gt;

&lt;p&gt;The answer to that is a very long one. &lt;br&gt;
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.&lt;/p&gt;

&lt;p&gt;Confused Yet?&lt;/p&gt;

&lt;p&gt;Let us write our web server first.&lt;br&gt;
We are going to use a go package called gin or gin-gonic.&lt;/p&gt;

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

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;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") 



}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the program above We import the packages &lt;code&gt;fmt&lt;/code&gt; and &lt;code&gt;gin&lt;/code&gt;&lt;br&gt;
In the main function We set up gin with defaults and listen on port &lt;code&gt;9000&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;You can now run that program with command.&lt;br&gt;
&lt;code&gt;go run main.go&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The server should be able to run but it cannot return anything to clients.&lt;br&gt;
 We handle this by creating a handler.&lt;br&gt;
Code below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;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")

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We have added the function &lt;code&gt;simpleHandler&lt;/code&gt; to handle &lt;code&gt;GET&lt;/code&gt; requests to endpoint at &lt;code&gt;/hello&lt;/code&gt;.&lt;/p&gt;

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

&lt;p&gt;&lt;code&gt;has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkej6437pem8wqxhvti7p.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkej6437pem8wqxhvti7p.png" alt="Example CORS Errors"&gt;&lt;/a&gt;&lt;/p&gt;

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

&lt;p&gt;Let us update our &lt;code&gt;main.go&lt;/code&gt; file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;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")

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



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

&lt;h2&gt;
  
  
  Next post will be about creating a News API/Web service.
&lt;/h2&gt;

</description>
      <category>go</category>
      <category>api</category>
      <category>beginners</category>
      <category>tutorial</category>
    </item>
  </channel>
</rss>
