• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Go的gin框架和gorm和html/template库

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

Gin 基础 :

Gin 的hello world :

package main

import (
    "github.com/gin-gonic/gin"
    "net/http"
)
func main()  {
    engine := gin.Default()
    engine.GET("/", func(context *gin.Context) {
        context.String(http.StatusOK,"hello world!")
    })
    engine.Run()
}
View Code

 

Gin 的 context.Params(path 参数) :

package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "net/http"
)
func main()  {
    engine := gin.Default()
    engine.GET("/:name/*rest", func(context *gin.Context) {
        context.String(http.StatusOK,"hello world!")
        fmt.Println(context.Params)
        params := context.Params
        fmt.Printf("%T\n", params)
        ret,ok := params.Get("name")
        if ok{
            fmt.Println(ret)
        }
        fmt.Println(params[0])      
    })

    engine.Run()
}
View Code

Gin 的 context.Query (get 参数):

package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "net/http"
)
func main()  {
    engine := gin.Default()
    engine.GET("/", func(context *gin.Context) {
        context.String(http.StatusOK,"hello world!")
        fmt.Println(context.Query("name")) // 如果不存在返回 空串  
        fmt.Println(context.DefaultQuery("name","none"))// 如果不存在返回 none  
    })
    engine.Run()
}
View Code

Gin 的 context.PostForm(post 参数):

package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "net/http"
)
func main()  {
    engine := gin.Default()
    engine.POST("/", func(context *gin.Context) {
        context.String(http.StatusOK,"hello world")
        fmt.Println(context.PostForm("name"))
        fmt.Println(context.DefaultPostForm("name","none"))
    })
    engine.Run()
}
View Code

Gin 的HTML渲染:

package main

import (
    "github.com/gin-gonic/gin"
    "html/template"
    "net/http"
)

func main() {
    eng := gin.Default()
    eng.SetFuncMap(template.FuncMap{
        "safe": func(s string)template.HTML {
            return template.HTML(s)
        },
    })
    eng.LoadHTMLGlob("templates/**/*")
    eng.GET("/test01", func(context *gin.Context) {
        context.HTML(http.StatusOK,"test/test01.html",gin.H{
            "a":`<a href="http://www.baidu.com">百度一下</a>`,
        })
    })
    eng.Run()
}
main.go
{{define "test/test01.html"}}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>posts/index</title>
</head>
<body>
    <h3>hello test01</h3>
    {{ .a | safe }}
</body>
</html>
{{end}}
templates/test/test01.html

注意:使用自定义模板函数的时候要先 SetFuncMap 后  LoadHTMLGlob  

 

当HTML文件中引用了静态文件时:

package main

import (
    "github.com/gin-gonic/gin"
    "html/template"
    "net/http"
)

func main() {
    eng := gin.Default()
    eng.SetFuncMap(template.FuncMap{
        "safe": func(s string)template.HTML {
            return template.HTML(s)
        },
    })
    eng.Static("/xxx","./static")
    eng.LoadHTMLGlob("templates/**/*")
    eng.GET("/test01", func(context *gin.Context) {
        context.HTML(http.StatusOK,"test/test01.html",gin.H{
            "a":`<a href="http://www.baidu.com">百度一下</a>`,
        })
    })
    eng.Run()
}
main.go
{{define "test/test01.html"}}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>posts/index</title>
</head>
<body>
    <h3>hello test01</h3>
    {{ .a | safe }}
    <script src="xxx/js/my.js"></script>
    <script>
        printHello()
    </script>
</body>
</html>
{{end}}
templates/test/test01.html
function printHello() {
    console.log("hello world!")
}
static/js/my.js

 

Gin 的文件上传:

单个文件上传:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <title>上传文件示例</title>
</head>
<body>
<form action="http://127.0.0.1:8080/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="f1">
    <input type="submit" value="上传">
</form>
</body>
</html>
upload.html
package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "log"
    "net/http"
)

func main()  {
    eng :=gin.Default()
    eng.POST("/upload", func(context *gin.Context) {
        file,err := context.FormFile("f1")
        if err != nil {
            context.JSON(http.StatusInternalServerError,gin.H{
                "msg":err.Error(),
            })
        }

        log.Println(file.Filename)
        dst := fmt.Sprintf("D:/temp/%s",file.Filename)
        context.SaveUploadedFile(file,dst)
        context.JSON(http.StatusOK,gin.H{
            "msg":fmt.Sprintf(`%s uploaded!`,file.Filename),
        })
    })
    eng.Run()


}
main.go

多个文件上传:

package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "log"
    "net/http"
)

func main()  {
    eng :=gin.Default()
    eng.POST("/upload", func(context *gin.Context) {
        // 多文件
        form,_ := context.MultipartForm()
        files := form.File["f1"]
        for idx,file := range files{
            log.Printf(file.Filename)
            dst := fmt.Sprintf("D:/temp/%s_%d",file.Filename,idx)
            context.SaveUploadedFile(file,dst)
            context.JSON(http.StatusOK,gin.H{
                "msg":fmt.Sprintf(`%s uploaded!`,file.Filename),
            })
        }
    })
    eng.Run()
}
main.go
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <title>上传文件示例</title>
</head>
<body>
<form action="http://127.0.0.1:8080/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="f1" multiple>
    <input type="submit" value="上传">
</form>
</body>
</html>
upload.html

 

Gin 的重定向:

package main

import (
    "github.com/gin-gonic/gin"
    "net/http"
)
func main()  {
    eng :=gin.Default()
    eng.GET("/test", func(context *gin.Context) {
        context.Redirect(http.StatusMovedPermanently,"http://www.baidu.com")
    })
    eng.Run()
}
main.go 

 

Gin 的请求的转发:

package main

import (
    "github.com/gin-gonic/gin"
    "net/http"
)
func main()  {
    eng :=gin.Default()
    eng.GET("/a", func(context *gin.Context) {
        context.Request.URL.Path = "/b"
        eng.HandleContext(context)
    })
    eng.GET("/b", func(context *gin.Context) {
        context.JSON(http.StatusOK,gin.H{
            "msg":"ok2",
        })
    })
    eng.Run()
}
main.go

 

Gin 的路由:

context.Any() 可以接受任何方式的请求,

context.NoRoute() 处理没有匹配的路由,404 请求,

package main

import (
    "github.com/gin-gonic/gin"
    "net/http"
)
func main()  {
    eng :=gin.Default()
    eng.LoadHTMLGlob("templates/*")
    eng.NoRoute(func(context *gin.Context) {
        context.HTML(http.StatusNotFound,"404.html",nil)
    })
    eng.Run()
}
main.go

路由组:

习惯性一对{}包裹同组的路由,只是为了看着清晰,用不用{}包裹功能上没什么区别。

package main

import (
    "github.com/gin-gonic/gin"
    "net/http"
)
func main()  {
    eng :=gin.Default()
    eng.LoadHTMLGlob("templates/*")
    eng.NoRoute(func(context *gin.Context) {
        context.HTML(http.StatusNotFound,"404.html",nil)
    })
    userGroup := eng.Group("/user")
    {
        userGroup.GET("/index", func(context *gin.Context) {
            context.JSON(http.StatusOK,gin.H{"msg":"user_index"})
        })
        userGroup.GET("/login", func(context *gin.Context) {
            context.JSON(http.StatusOK,gin.H{"msg":"user_login"})
        })
    }
    adminGroup := eng.Group("/admin")
    {
        adminGroup.GET("/index", func(context *gin.Context) {
            context.JSON(http.StatusOK,gin.H{"msg":"admin_index"})
        })
        adminGroup.GET("/login", func(context *gin.Context) {
            context.JSON(http.StatusOK,gin.H{"msg":"admin_login"})
        })
    }
    eng.Run()
}
main.go

路由组也可以嵌套:

package main

import (
    "github.com/gin-gonic/gin"
    "net/http"
)
func main()  {
    eng :=gin.Default()
    eng.LoadHTMLGlob("templates/*")
    eng.NoRoute(func(context *gin.Context) {
        context.HTML(http.StatusNotFound,"404.html",nil)
    })
    userGroup := eng.Group("/user")
    {
        userGroup.GET("/index", func(context *gin.Context) {
            context.JSON(http.StatusOK,gin.H{"msg":"user_index"})
        })
        userGroup.GET("/login", func(context *gin.Context) {
            context.JSON(http.StatusOK,gin.H{"msg":"user_login"})
        })
        vipGroup := userGroup.Group("/vip")
        {
            vipGroup.GET("/index", func(context *gin.Context) {
                context.JSON(http.StatusOK,gin.H{"msg":"user_vip_index"})
            })
            vipGroup.GET("/login", func(context *gin.Context) {
                context.JSON(http.StatusOK,gin.H{"msg":"user_vip_login"})
            })
        }
    }
    adminGroup := eng.Group("/admin")
    {
        adminGroup.GET("/index", func(context *gin.Context) {
            context.JSON(http.StatusOK,gin.H{"msg":"admin_index"})
        })
        adminGroup.GET("/login", func(context *gin.Context) {
            context.JSON(http.StatusOK,gin.H{"msg":"admin_login"})
        })
    }
    eng.Run()
}
main.go

Gin 的绑定数据到结构体上:

form表单,json格式,

package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "net/http"
)

type myData struct {
    Username string `form:"username" json:"user" binding:"required"`
    Password string `form:"password" json:"pwd" binding:"required"`
}
func main()  {
    eng :=gin.Default()
    eng.POST("/", func(context *gin.Context) {
        var d myData
        // Content-type 为 multipart/form-data // POST 表单上传
        //err := context.Bind(&d) // Bind 可以解析form 格式
        //if err != nil {
        //    fmt.Println("bind data to struct failed,err:",err)
        //    return
        //}
        //fmt.Println(d.Username)
        //fmt.Println(d.Password)

        //Content-type 为 application/json 格式
        err := context.ShouldBindUri(&d)
        if err != nil {
            fmt.Println("bind data to struct failed,err:",err)
            return
        }
        fmt.Println(d.Username)
        fmt.Println(d.Password)
        context.JSON(http.StatusOK,gin.H{"msg":"ok"})
    })

    eng.Run()
}
main.go

uri:(path 路径)

package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "net/http"
)

type myData struct {
    Username string `uri:"name" binding:"required"`
    Password string `uri:"pwd"  binding:"required"`
}
func main()  {
    eng :=gin.Default()
    eng.GET("/:name/:pwd", func(context *gin.Context) {
        var d myData
        err := context.ShouldBindUri(&d)
        if err != nil {
            fmt.Println("bind data to struct failed,err:",err)
            return
        }
        fmt.Println(d.Username)
        fmt.Println(d.Password)

        context.JSON(http.StatusOK,gin.H{"msg":"ok"})
    })
    eng.Run()
}
main.go

 

Gin 的中间件: 

全局中间件(contex.Next() 和 context.Abort() )

package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "net/http"
    "time"
)

// 请求耗时的中间件函数
func countReqTime()gin.HandlerFunc  {
    return func(context *gin.Context) {
        start := time.Now()
        m := make(map[string]interface{})
        m["name"] = "tom"
        m["age"] = 18
        context.Set("data",m) // 可以通过context.Set在请求上下文中设置值,后续的处理函数能够取到该值

        time.Sleep(time.Second)

        res := time.Since(start)
        fmt.Println("耗时:",res)
        context.Next()


    }
}
// 打印 hello world 的中间件
func printHello()gin.HandlerFunc  {
    return func(context *gin.Context) {
        fmt.Println("hello world")

        context.Next() // 如果使用 context.Abort()  请求会到此返回,洋葱模型
    }
}

func main()  {
    eng :=gin.Default()
    // 注册两个全局中间件
    eng.Use(printHello())
    eng.Use(countReqTime())
    // {} 是为了代码规范
    eng.GET("/", func(context *gin.Context) {
        fmt.Println(context.Get("data"))
        context.JSON(http.StatusOK,gin.H{"msg":"ok"})
    })
    eng.Run()
}
main.go

 

局部中间件(给单个路由 设置中间件)

package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "net/http"
)

// 打印 hello world 的中间件
func printHello()gin.HandlerFunc  {
    return func(context *gin.Context) {
        fmt.Println("hello world")

        context.Next() // 如果使用 context.Abort()  请求会到此返回,洋葱模型
    }
}

func main()  {
    eng :=gin.Default()
    eng.GET("/",printHello(), func(context *gin.Context) {
        context.JSON(http.StatusOK,gin.H{"msg":"ok"})
    })
    eng.Run()
}
main.go

 

给路由组加上中间件:

package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "net/http"
)

func printHello() gin.HandlerFunc  {
    return func(context *gin.Context) {
        fmt.Println("hello world")
        context.Next()
    }
}


func main()  {
    eng :=gin.Default()
    eng.LoadHTMLGlob("templates/*")
    eng.NoRoute(func(context *gin.Context) {
        context.HTML(http.StatusNotFound,"404.html",nil)
    })
    // 方式一
    //userGroup := eng.Group("/user",printHello())
    //{
    //    userGroup.GET("/index", func(context *gin.Context) {
    //        context.JSON(http.StatusOK,gin.H{"msg":"user_index"})
    //    })
    //    userGroup.GET("/login", func(context *gin.Context) {
    //        context.JSON(http.StatusOK,gin.H{"msg":"user_login"})
    //    })
    //}

    // 方式二
    userGroup := eng.Group("/user")
    userGroup.Use(printHello())
    {
        userGroup.GET("/index", func(context *gin.Context) {
            context.JSON(http.StatusOK,gin.H{"msg":"user_index"})
        })
        userGroup.GET("/login", func(context *gin.Context) {
            context.JSON(http.StatusOK,gin.H{"msg":"user_login"})
        })
    }


    eng.Run()
}
main.go

 

默认中间件:

 

 

Gin 的获取设置Cookie: 

package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
)

func main()  {
    eng :=gin.Default()
    eng.GET("/", func(context *gin.Context) {
        // 获取客户端cookie
        cookie,err := context.Cookie("xxx" 
                       
                    
                    

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Go package(3):io包介绍和使用发布时间:2022-07-10
下一篇:
GO入门——5. 函数发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap