后台管理 GIN-VUE-ADMIN http://doc.henrongyi.top/
安装gin go install github.com/gin-gonic/gin@latest 10M

package main
import "github.com/gin-gonic/gin"

func main() {
    gin.SetMode(gin.ReleaseMode)//正式环境使用
    r := gin.Default()
    r.GET("/", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "message": "pong" + c.ClientIP(),
        })
    })
    r.Run(":8888")
    gin.SetMode(gin.DebugMode) debug
    gin.DisableConsoleColor() //禁用控制台输出
   r := gin.Default()

   data :=gin.H{"email": "foo@bar.com", "phone": 200}//map[string]interface{}快捷方式
data :=gin.Accounts{
            "foo":    "bar",
            "austin": "1234",
            "lena":   "hello2",
            "manu":   "4321",
        }//map[string]string快捷方式

   r.GET("/ui/*filepath", gin.WrapH(http.FileServer(http.FS(dir))))//静态文件
   r.GET("/", func(c *gin.Context) {
    username := c.PostForm("username")
    ip := c.ClientIP() //客户端ip
      c.String(200, "Hell=%s",username)
      c.JSON(200, gin.H{"message": "pong",})
c.AsciiJSON(http.StatusOK, data)
c.IndentedJSON()美化json
c.JSONP(http.StatusOK, data)
ua := c.GetHeader("User-Agent")//Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36 Edg/87.0.664.66
c.PureJSON(200, gin.H{"message": "<b>Hello, world!</b>", "status": 200}) //html<符号不转义
c.JSON(http.StatusOK, gin.H{"message": "hey", "status": 200})
c.XML(200, gin.H{"message": "hey", "status": 200})
c.YAML(200, gin.H{"message": "hey", "status": 200})
c.File("./ui/favicon.png") //直接访问
c.FileAttachment("./ui/favicon.png","1.jpg") //下载指定文件名
c.HTML(http.StatusOK, "index.tmpl", gin.H{//渲染模板
            "title": "Main website",
        })
c.Header("site","tizi365") //发送到头部

c.SetCookie("site_cookie", "我爱你", 3600, "/", "", false, true)//设置cookie,最后三个参数是 域名,是否只支持https,js是否允许读
data, _ := c.Cookie("site_cookie")//读取cookie
c.SetCookie("site_cookie", "", -1,"/","",false,true)//删除cookie
   })
   结束-------------------------------

c.Redirect(301, "http://www.google.com/") //跳转
 c.Request.URL.Path = "/test2"
    r.HandleContext(c) //内部跳转

   r.GET("/someGet", getting) //路由
    r.POST("/somePost", posting)
    r.PUT("/somePut", putting)
    r.DELETE("/someDelete", deleting)
    r.PATCH("/somePatch", patching)
    r.HEAD("/someHead", head)
    r.OPTIONS("/someOptions", options)

r.LoadHTMLGlob("templates/*") //加载模板目录
`r.LoadHTMLGlob("templates/**/*")//加载templates目录下面的所有模版文件,包括子目录不能包含非模板文件`
r.LoadHTMLFiles("templates/template1.html","templates/template2.html")//加载文件

lastname := c.Query("lastname") get获取string 不存在返回空字符串
id, ok := c.GetQuery("id") if(!ok){//如果不存在}
c.QueryArray("id")[]string 不存在返回空数组
c.GetQueryArray("id")[]string,bool
c.QueryMap("id")map[string]string 不存在返回空map ?ids[qq]=wo&ids[rt]=我
c.GetQueryMap("id") map[string]string,isok 返回一个是否存在
ids:= c.DefaultQuery("ids","11")key不存在取11


name := c.PostForm("name") post获取string 不存在返回空字符串
id, ok := c.GetPostForm("id") 第二个参数返回bool
c.PostFormArray("id")[]string 不存在空数组
c.GetPostFormyArray("id")[]string,bool
names := c.PostFormMap("names")map[string]string 不存在空map
c.GetPostFormMap("id") map[string]string,isok 返回一个是否存在
name := c.DefaultPostForm("name", "tizi365")

type User struct {
    Name string `json:"name" form:"name"`
}//绑定到结构体,axios使用,发送的是json
var u User
c.BindJSON(&u)

data:=c.Param("name")//路由参数 /:name

v1 := router.Group("/v1")//路由组
{
        v1.POST("/login", loginEndpoint)
        v1.POST("/submit", submitEndpoint)
        v1.POST("/read", readEndpoint)
 }

r.Static("/assets", "./assets")//静态目录服务器
r.StaticFS("/weui",gin.Dir("weui",false)) //静态资源服务器常用,true是列出文件
r.StaticFile("/","ui/index.html")//自动访问首页
r.StaticFile("/favicon.ico", "./resources/favicon.ico")//托管单文件

//日志输出到文件
    f, _ := os.Create("gin.log")
    gin.DefaultWriter = io.MultiWriter(f)

r.Run(":8888")
}

上传
router.MaxMultipartMemory = 64 << 20//上传大小64MB
file, _ := c.FormFile("file") 上传
 log.Println(file.Filename) //上传文件名
c.SaveUploadedFile(file, "./data/1.jpg") 保存

form, _ := c.MultipartForm()//多文件
files := form.File["upload[]"]
for _, file := range files {
 log.Println(file.Filename)
c.SaveUploadedFile(file, dst)
        }
base64编码输出图片
i := strings.Index(b64s, ",")
dec := base64.NewDecoder(base64.StdEncoding, strings.NewReader(b64s[i+1:]))
c.Header("Content-Type","image/png")
io.Copy(c.Writer, dec)
  • 中间件
    authorized := r.Group("/admin", gin.BasicAuth(gin.Accounts{
        "foo":    "bar",
        "austin": "1234",
        "lena":   "hello2",
        "manu":   "4321",
    }))
    authorized.GET("/secrets", func(c *gin.Context) {
        // 获取用户,它是由 BasicAuth 中间件设置的
        user := c.MustGet(gin.AuthUserKey).(string)
        if secret, ok := secrets[user]; ok {
            c.JSON(http.StatusOK, gin.H{"user": user, "secret": secret})
        } else {
            c.JSON(http.StatusOK, gin.H{"user": user, "secret": "NO SECRET :("})
        }
    })
  • session
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
"github.com/gin-contrib/sessions/redis"
store := cookie.NewStore([]byte("secret"))//secret是密钥
store, _ := redis.NewStore(10, "tcp", "localhost:6379", "", []byte("secret"))//使用redis

r.Use(sessions.Sessions("mysession", store))//使用中间件
r.GET("/c", func(c *gin.Context) {
        session := sessions.Default(c)//初始化
        if session.Get("hello") != "world" {
            session.Set("hello", "world")
            session.Save()
            session.Delete("tizi365")//删除session
            session.Clear()//清空session
        }
        c.JSON(200,gin.H{"hello": session.Get("hello")})
    })
  • 模板,防止转义定义字符串
    var template.HTML ss=<a></a>

    {{range .data}}
    {{.Qishu}}
    {{end}}
    {{ range $k, $v := .data }}
      <p>
          <span>{{$k}}</span>
          <span>{{$v.Id}}</span>
      </p>
      {{ end }}
    {{if gt .Age 18}}
              <p>hello, old man, {{.Name}}</p>
              {{else}}
              <p>hello,young man, {{.Name}}</p>
              {{end}}
    •   not 非{{if not .condition}} {{end}}
    •   and 与{{if and .condition1 .condition2}} {{end}}
    •   or 或{{if or .condition1 .condition2}} {{end}}
    •   eq 等于{{if eq .var1 .var2}} {{end}}
    •   ne 不等于{{if ne .var1 .var2}} {{end}}
    •   lt 小于 (less than){{if lt .var1 .var2}} {{end}}
    •   le 小于等于{{if le .var1 .var2}} {{end}}
    •   gt 大于{{if gt .var1 .var2}} {{end}}
    •   ge 大于等于{{if ge .var1 .var2}} {{end}}
    {{with .User}}
    {{range .}}
    <input type="radio" name="test" value={{.Name}}/>{{.Name}}<br/>
    {{end}}
    {{end}}
  • 中间件 jwt

package main

import (
    "fmt"
    jwt "github.com/appleboy/gin-jwt/v2"
    "github.com/gin-gonic/gin"
    "log"
    "net/http"
    "time"
)

type login struct {
    Username string `form:"username" json:"username" binding:"required"`
    Password string `form:"password" json:"password" binding:"required"`
}

var (
    identityKey = "id"
)

// User demo
type User struct {
    UserName  string
    FirstName string
    LastName  string
}

func main() {
    fmt.Println("hello world")
    r := gin.Default()
    // the jwt middleware
    authMiddleware, err := jwt.New(initParams())
    if err != nil {
        log.Fatal("JWT Error:" + err.Error())
    }

    // register middleware
    r.Use(handlerMiddleWare(authMiddleware))

    // register route
    registerRoute(r, authMiddleware)

    // start http server
    if err = http.ListenAndServe(":8000", r); err != nil {
        log.Fatal(err)
    }

}

func registerRoute(r *gin.Engine, handle *jwt.GinJWTMiddleware) {
    r.POST("/login", handle.LoginHandler) //登陆 localhost:8000/login username=admin password=admin
    r.NoRoute(handle.MiddlewareFunc(), handleNoRoute())

    auth := r.Group("/auth", handle.MiddlewareFunc())
    auth.GET("/refresh_token", handle.RefreshHandler) //刷新令牌 auth/refresh_token "Authorization:Bearer xxxxxxxxx"  "Content-Type: application/json"

    auth.GET("/hello", helloHandler) //登陆响应 localhost:8000/auth/hello "Authorization:Bearer xxxxxxxxx"  "Content-Type: application/json"

}

func handlerMiddleWare(authMiddleware *jwt.GinJWTMiddleware) gin.HandlerFunc {
    return func(context *gin.Context) {
        errInit := authMiddleware.MiddlewareInit()
        if errInit != nil {
            log.Fatal("authMiddleware.MiddlewareInit() Error:" + errInit.Error())
        }
    }
}
func initParams() *jwt.GinJWTMiddleware {
    return &jwt.GinJWTMiddleware{
        Realm:       "test zone",
        Key:         []byte("secret key"),
        Timeout:     time.Hour,
        MaxRefresh:  time.Hour,
        IdentityKey: identityKey,
        PayloadFunc: payloadFunc(),

        IdentityHandler: identityHandler(),
        Authenticator:   authenticator(),
        Authorizator:    authorizator(),
        Unauthorized:    unauthorized(),
        TokenLookup:     "header: Authorization, query: token, cookie: jwt",
        // TokenLookup: "query:token",
        // TokenLookup: "cookie:token",
        TokenHeadName: "Bearer",
        TimeFunc:      time.Now,
    }
}

func payloadFunc() func(data interface{}) jwt.MapClaims {
    return func(data interface{}) jwt.MapClaims {
        if v, ok := data.(*User); ok {
            return jwt.MapClaims{
                identityKey: v.UserName,
            }
        }
        return jwt.MapClaims{}
    }
}

func identityHandler() func(c *gin.Context) interface{} {
    return func(c *gin.Context) interface{} {
        claims := jwt.ExtractClaims(c)
        return &User{
            UserName: claims[identityKey].(string),
        }
    }
}

func authenticator() func(c *gin.Context) (interface{}, error) {
    return func(c *gin.Context) (interface{}, error) {
        var loginVals login
        if err := c.ShouldBind(&loginVals); err != nil {
            return "", jwt.ErrMissingLoginValues
        }
        userID := loginVals.Username
        password := loginVals.Password

        if (userID == "admin" && password == "admin") || (userID == "test" && password == "test") {
            return &User{
                UserName:  userID,
                LastName:  "Bo-Yi",
                FirstName: "Wu",
            }, nil
        }
        return nil, jwt.ErrFailedAuthentication
    }
}

func authorizator() func(data interface{}, c *gin.Context) bool {
    return func(data interface{}, c *gin.Context) bool {
        if v, ok := data.(*User); ok && v.UserName == "admin" {
            return true
        }
        return false
    }
}

func unauthorized() func(c *gin.Context, code int, message string) {
    return func(c *gin.Context, code int, message string) {
        c.JSON(code, gin.H{
            "code":    code,
            "message": message,
        })
    }
}

func handleNoRoute() func(c *gin.Context) {
    return func(c *gin.Context) {
        claims := jwt.ExtractClaims(c)
        log.Printf("NoRoute claims: %#v\n", claims)
        c.JSON(404, gin.H{"code": "PAGE_NOT_FOUND", "message": "Page not found"})
    }
}

func helloHandler(c *gin.Context) {
    claims := jwt.ExtractClaims(c)
    user, _ := c.Get(identityKey)
    c.JSON(200, gin.H{
        "userID":   claims[identityKey],
        "userName": user.(*User).UserName,
        "text":     "Hello World.",
    })
}
作者:Yoby  创建时间:2020-07-26 22:36
 更新时间:2024-12-05 13:26
上一篇:
下一篇: