Summary of recent use of gin

Time:2021-1-17

Recently, a new project is developed by using gin. Some problems are encountered in the process. To sum up, as a note, I hope it can help you.

Cross domain problems

Middleware:

func Cors() gin.HandlerFunc {
    return func(c *gin.Context) {
        //Here you can use * or the domain name you specify
        c.Header("Access-Control-Allow-Origin", "*")
        //Allow header parameters
        c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token")
        //Allowed methods
        c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
        c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
        c.Header("Access-Control-Allow-Credentials", "true")

        method := c.Request.Method
        //Release options method
        if method == "OPTIONS" {
            c.AbortWithStatus(http.StatusOK)
        }
        //Processing requests
        c.Next()
    }
}

Then add the following in the route:

// g : *gin.Engine
g.Use(Cors())

Of course, it can also be configured in the nginx layer. You can check it yourself. I will not expand it.

Using multiple Middleware

// g : *gin.Engine
g.Use(Cors())
g.Use(Session())

Middleware termination request

func Auth() gin.HandlerFunc {
    return func(c *gin.Context) {
        uid := c.MustGet("uid").(int)
        if uid == 0 {
            c.Abort()
            controller.SendResponse (C, 401, "not logged in", Nil)
            //Return can be ignored
            return
        } else {
            c.Next()
        }
    }
}

Session usage

package util

import (
    "github.com/gin-gonic/gin"
    "github.com/gin-contrib/sessions"
    "github.com/gin-contrib/sessions/redis"
    redisGo "github.com/gomodule/redigo/redis"
    "github.com/spf13/viper"
)

//Start session
func SessionStart(g *gin.Engine, RedisClient *redisGo.Pool, key ...[]byte)  {
    store, _ := redis.NewStoreWithPool(RedisClient, []byte(viper.GetString("name")))
    redis.SetKeyPrefix(store, "session_")
    g.Use(sessions.Sessions(viper.GetString("name"), store))
}

//Using session
session  := sessions.Default(c)
session.Set("uid", uid)
uid  := session.Get("uid")

Upload OSS

import (
    "os"

    "github.com/aliyun/aliyun-oss-go-sdk/oss"
    "github.com/spf13/viper"
)
func upload(localPath string, iType int, Name string) (path string) {
    client, err := oss.New(viper.GetString("oss.end_point"), viper.GetString("oss.access_key_id"), viper.GetString("oss.access_key_secret"))
    if err != nil {
        return 
    }

    //Get the storage space.
    bucket, err := client.Bucket(viper.GetString("oss.bucket"))
    if err != nil {
        return 
    }

    //Upload local files.
    ossPath := fmt.Sprintf("%s/%s", "qiling", Name)
    err = bucket.PutObjectFromFile(ossPath, localPath)
    if err != nil {
        return
    }

    path = fmt.Sprintf("%s/%s", viper.GetString("oss.hosts"), ossPath)
    os.Remove(localPath)
    return
}

Several practical methods

package util

import (
    "fmt"
    "bytes"
    "strings"
    "time"    
    "unicode/utf8"
    "strconv"
    "crypto/md5"
    "net/http"
    "net/url"
    "io/ioutil"
)


//Get this week's time stamp
func GetFirstDateOfWeekTS() (ts int64) {
    now := time.Now()

    offset := int(time.Monday - now.Weekday())
    if offset > 0 {
        offset = -6
    }

    ts = time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local).AddDate(0, 0, offset).Unix()
    return
}

//Get week time stamp
func GetWeekTS(day int64) (ts int64) {
    thisWeekMonday := GetFirstDateOfWeekTS()
    ts = thisWeekMonday + (day)*86400
    return
}

//String length
func StrLen(str string) int {
    return utf8.RuneCountInString(str)
}

//Intercept string
func StrSub(str string, sub ...int) string {
    start := sub[0]
    length := 0
    if len(sub) > 1 {
        length = sub[1]
    }

    if length < 1 {
        return string(([]rune(str))[start:])
    }
    return string(([]rune(str))[start:length])
}

//Merge strings
func StrCombine(str ...string) string {
    var bt bytes.Buffer
    for _, arg := range str {
        bt.WriteString(arg)
    }
    //Get the stitched string
    return bt.String()
}

func UnicodeIndex(str,substr string) int {
    //Substring at byte position of string
    result := strings.Index(str,substr)  
    if result >= 0 {
      //Get the string before the substring and convert it to [] byte
      prefix := []byte(str)[0:result]  
      //Convert the string before the substring to [] run
      rs := []rune(string(prefix))  
      //The length of the string before the substring is the character position of the substring in the string
      result = len(rs)
    }

    return result
}

func ToUnicode(str string) string {
    textQuoted := strconv.QuoteToASCII(str)
    return textQuoted[1 : len(textQuoted)-1]
}

func UnicodeTo(str string) string {
    sUnicodev := strings.Split(str, "\u")
    var context string
    for _, v := range sUnicodev {
        if len(v) < 1 {
            continue
        }
        temp, err := strconv.ParseInt(v, 16, 32)
        if err != nil {
            panic(err)
        }
        context += fmt.Sprintf("%c", temp)
    }
    return context
}

//Get the 0:00 time of the day
func TodayTS() int64 {
    now := time.Now()
    return GetZeroTime(now).Unix()
}

func TodayDate()  string {
    return time.Now().Format("2006/01/02")
}

//Gets the first day of the month in which the incoming time is located, that is, 0 o'clock on the first day of a month. As in time.Now (), returns the 0:00 time of the first day of the current month.
func GetFirstDateOfMonth(d time.Time) time.Time {
    d = d.AddDate(0, 0, -d.Day() + 1)
    return GetZeroTime(d)
}
//Gets the last day of the month in which the incoming time is located, that is, 0 point on the last day of a month. As in time.Now (), returns the 0:00 time of the last day of the current month.
func GetLastDateOfMonth(d time.Time) time.Time {
    return GetFirstDateOfMonth(d).AddDate(0, 1, -1)
}

//Get 0:00 time of a day
func GetZeroTime(d time.Time) time.Time {
    return time.Date(d.Year(), d.Month(), d.Day(), 0, 0, 0, 0, d.Location())
}

func Md5(str string) string {
    return fmt.Sprintf("%x", md5.Sum([]byte(str)));
}

func HttpGet(iUrl string, params map[string]string) ([]byte, error) {
    query := ""
    for k, v := range params {
        query = fmt.Sprintf("%s%s=%s&", query, k, url.QueryEscape(v))
    }

    client :=  http.Client {Timeout: 5 *  time.Second }// create a client
    resp, err := client.Get(fmt.Sprintf("%s?%s", iUrl, query))
    fmt.Println(iUrl,query)

    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()
    res, err := ioutil.ReadAll(resp.Body)
    if err!=nil{
        fmt.Println(err)
        return nil,err
    }

    return res, nil
}

That’s about it. There’s something to share later.


go

This work adoptsCC agreementReprint must indicate the author and the link of this article

Before the collection, you may as well order a like to try!!!