Carlos Aguni

Highly motivated self-taught IT analyst. Always learning and ready to explore new skills. An eternal apprentice.


Golang gonic gin template

15 Sep 2022 »
  • Utils
    • send file attachment
      • https://stackoverflow.com/questions/31638447/how-to-server-a-file-from-a-handler-in-golang
    • cors
      • https://stackoverflow.com/questions/29418478/go-gin-framework-cors

install go

curl -OL https://go.dev/dl/go1.19.1.linux-amd64.tar.gz
tar xzvf go1.19.1.linux-amd64.tar.gz -C /usr/local
echo 'export PATH="/usr/local/go/bin:$PATH"' >> ~/.bashrc
. ~/.bashrc
go mod init test/test
package main

import (
        //"encoding/json"
        //"fmt"
        //"io/ioutil"
        //"log"
        "net/http"
        //"strings"

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

func main() {
        engine := gin.New()
    engine.Use(CORSMiddleware())
        engine.GET("/", func(c *gin.Context) {
                c.JSON(http.StatusOK, gin.H{
                        "message": "hello world",
                })
        })
        engine.GET("/file.csv", func(c *gin.Context) {
             c.FileAttachment("./file.csv","file.csv")
        })
        engine.Run(":3000")
}

func CORSMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {

        c.Header("Access-Control-Allow-Origin", "*")
        c.Header("Access-Control-Allow-Credentials", "true")
        c.Header("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
        c.Header("Access-Control-Allow-Methods", "POST,HEAD,PATCH, OPTIONS, GET, PUT")

        if c.Request.Method == "OPTIONS" {
            c.AbortWithStatus(204)
            return
        }

        c.Next()
    }
}