分类: Go

复盘web库gin框架

安装

go get -u github.com/gin-gonic/gin

基础使用

package main

import (
  "net/http"

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

func main() {
  r := gin.Default()
  r.GET("/ping", func(c *gin.Context) {
    c.JSON(http.StatusOK, gin.H{
      "message": "pong",
    })
  })
  r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}

复杂使用

gin.SetMode(gin.ReleaseMode)
router := gin.Default()

// 不存在的路由
router.NoRoute(controller.NotFound)
// 不存在的方法
router.NoMethod(controller.NotFound)
// 静态文件目录
//router.Static("/files", "./files")
// 静态文件
router.StaticFile("/favicon.ico", "./static/favicon.ico")
// 静态文件目录
router.Static("/static", "./static")
// 模板标签
router.Delims("{{{", "}}}")
// 模板加载路径
router.LoadHTMLGlob("views/**/**/*")
// 模板调用函数
router.SetFuncMap(template.FuncMap{
    "SafeJs":              view.SafeJS,
})

// 使用中间件
router.Use(middleware.Cors())
// 实例化控制器
controllersV1 := new(v1.Controller)

// 路由分组
api := router.Group("api")
{
    // 无需权限校验的分组
    apiV1 := api.Group("v1")
    {
        // 设置路由 POST、GET等
        apiV1.GET("user/test_a", controllersV1.TestA)
        apiV1.GET("user/test_b", controllersV1.TestB)
        apiV1.POST("user/test_c", controllersV1.TestC)
    }
    // 需要权限校验的分组
    apiV1.Use(middleware.JWTAuth())
    {
        apiV1.GET("user/test_d", controllersV1.TestD)
    }

    // 需要权限校验
    //apiV1.Use(middleware.CasbinRBAC())

}
router.Run()

中间件的编写

// 跨域中间件
// Cors 处理跨域请求,支持options访问
func Cors() gin.HandlerFunc {
    return func(c *gin.Context) {
        method := c.Request.Method
        origin := c.Request.Header.Get("Origin")
        c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
        c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token,X-Token,X-User-Id")
        c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS,DELETE,PUT")
        c.Writer.Header().Set("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
        c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
        // 放行所有OPTIONS方法
        if method == "OPTIONS" {
            c.AbortWithStatus(http.StatusNoContent)
        }
        // 处理请求
        c.Next()
    }
}
// JWT 处理中间件
func JWTAuth() gin.HandlerFunc {
    return func(c *gin.Context) {
        // jwt鉴权取头部信息 x-token 登录时回返回token信息 这里前端需要把token存储到cookie或者本地localStorage中 不过需要跟后端协商过期时间 可以约定刷新令牌或者重新登录
        token := c.Request.Header.Get("x-token")
        if token == "" {
            c.JSON(http.StatusUnauthorized, gin.H{"error": "未登录或非法访问"})
            c.Abort()
            return
        }
        fmt.Println("JWTAuth")
        c.Set("claims", 11)
        c.Next()
    }
}

控制器

# 结构体形式的控制器
type IndexApi struct {
}

// Index
func (a IndexApi) Index(c *gin.Context) {
    c.JSON(200, gin.H{"message": "hello world"})
}
# 单个函数控制器方法
func Index(c *gin.Context) {
    c.JSON(200, gin.H{"message": "hello world"})
}

数据输出

c.JSON(200, gin.H{"message": "hello world"})
其他的善用搜索与文档

对Go的复盘计划

距离上一次的go工作已经过去差不多一年半了,最近一年半PHP为主了,对go又生疏了。
接下来开始重新学习go,放下的再捡起来吧

goutil/dump – 打印漂亮易读的go数据

gookit/goutil/dump - 是一个golang数据打印工具包,可以打印出漂亮易读的go slice, map, struct数据。

主要功能:
使用简单,直接调用 dump.P(vars...) 即可
支持所有的基础数据类型
支持slice, map, struct数据结构
支持传入打印多个变量
默认输出调用位置,方便使用
支持自定义部分能力,如 缩进,色彩主题等

打印基础类型

package main

import "github.com/gookit/goutil/dump"

// rum demo:
//     go run ./dump/_examples/basic_types.go
func main() {
    dump.P(
        nil, true,
        12, int8(12), int16(12), int32(12), int64(12),
        uint(22), uint8(22), uint16(22), uint32(22), uint64(22),
        float32(23.78), float64(56.45),
        'c', byte('d'),
        "string",
    )
}

打印slice

打印 array, slice 都会一行一个元素输出,同时会在最后输出长度。

package main

import "github.com/gookit/goutil/dump"

// rum demo:
//     go run ./dump/_examples/slice.go
func main() {
    dump.P(
        []byte("abc"),
        []int{1, 2, 3},
        []string{"ab", "cd"},
        []interface{}{
            "ab",
            234,
            []int{1, 3},
            []string{"ab", "cd"},
        },
    )
}

打印map

打印map数据结构,会一行一个元素输出,同时会在最后输出map长度。

package main

import "github.com/gookit/goutil/dump"

// rum demo:
//     go run ./map.go
//     go run ./dump/_examples/map.go
func main() {
    dump.P(
        map[string]interface{}{
            "key0": 123,
            "key1": "value1",
            "key2": []int{1, 2, 3},
            "key3": map[string]string{
                "k0": "v0",
                "k1": "v1",
            },
        },
    )
}

打印struct

打印struct数据,指针类型会自动打印底层真实数据

package main

import (
    "fmt"

    "github.com/gookit/color"
    "github.com/gookit/goutil/dump"
)

// rum demo:
//     go run ./struct.go
//     go run ./dump/_examples/struct.go
func main() {
    s1 := &struct {
        cannotExport map[string]interface{}
    }{
        cannotExport: map[string]interface{}{
            "key1": 12,
            "key2": "abcd123",
        },
    }

    s2 := struct {
        ab string
        Cd int
    }{
        "ab", 23,
    }

    color.Infoln("- Use fmt.Println:")
    fmt.Println(s1, s2)

    color.Infoln("\n- Use dump.Println:")
    dump.P(
        s1,
        s2,
    )
}

自定义dumper

支持自定义dumper一些选项。如 缩进,色彩主题等

// Options for dump vars
type Options struct {
    // Output the output writer
    Output io.Writer
    // NoType dont show data type TODO
    NoType bool
    // NoColor don't with color
    NoColor bool
    // IndentLen width. default is 2
    IndentLen int
    // IndentChar default is one space
    IndentChar byte
    // MaxDepth for nested print
    MaxDepth int
    // ShowFlag for display caller position
    ShowFlag int
    // MoreLenNL array/slice elements length > MoreLenNL, will wrap new line
    // MoreLenNL int
    // CallerSkip skip for call runtime.Caller()
    CallerSkip int
    // ColorTheme for print result.
    ColorTheme Theme
}

在 CentOS 上安装 Go 语言 (Golang) 的步骤如下

步骤一:更新系统

首先,确保系统的软件包是最新的。打开终端并执行以下命令:

sudo yum update -y

步骤二:下载 Go 语言安装包

前往 Go 语言官方网站 下载适用于 Linux 的最新版本安装包。你也可以使用 wget 命令直接下载。例如:

wget https://golang.org/dl/go1.20.1.linux-amd64.tar.gz
wget https://go.dev/dl/go1.22.4.linux-amd64.tar.gz

请根据最新的 Go 版本替换 URL 中的版本号。

步骤三:解压安装包

下载完成后,将压缩包解压到 /usr/local 目录:

tar zxvf go1.8.linux-amd64.tar.gz  -C  /usr/local
或
sudo tar -C /usr/local -xzf go1.20.1.linux-amd64.tar.gz

步骤四:设置环境变量

要使 Go 语言生效,需要配置环境变量。打开你的 shell 配置文件,例如 .bashrc 或 .profile,并添加以下行:

vim /etc/profile

# 添加如下内容
# GO相关
export GOROOT=/usr/local/go
export GOBIN=$GOROOT/bin
export PATH=$PATH:$GOBIN

# 将用户GOBIN加入到PATH
export GOPATH=/home/iuu/Developer/go
export GOBIN=$GOPATH/bin
export PATH=$PATH:$GOBIN

执行以下命令以使配置文件生效:

# 完成后执行
source /etc/profile

步骤五:验证安装

验证 Go 语言是否成功安装,可以通过以下命令检查:

go version

如果安装成功,你会看到类似如下的输出:

go version go1.20.1 linux/amd64

番外篇

为了方便管理 Go 项目,你可以设置一个 Go 工作区。创建一个工作目录,例如:

mkdir -p /home/iuu/Developer/go/{bin,src,pkg}

然后在你的 shell 配置文件中添加以下行:

export GOPATH=/home/iuu/Developer/go
export PATH=$PATH:$GOPATH/bin

再次执行 source ~/.bashrc 或 source ~/.profile 使配置生效。
现在你已经成功在 CentOS 上安装并配置了 Go 语言环境,可以开始编写和运行 Go 语言程序了。

1 2