golang中gin框架的基礎學習和運用
阿新 • • 發佈:2019-01-23
1.安裝
go get gopkg.in/gin-gonic/gin.v1
2.基本的架構
2.1 直接呼叫方案
package main import ( "github.com/gin-gonic/gin" "net/http" ) func main() { r := gin.Default() r.GET("/ping", func(c *gin.Context) { name := c.Query("name") c.String(http.StatusOK, "Hello %s", name) }) //預設監聽8080 r.Run(":80") }
2.2 函式方案
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func pings(c *gin.Context) {
name := c.Query("name")
c.String(http.StatusOK, "Hello %s", name)
}
func main() {
r := gin.Default()
r.GET("/ping", pings)
//預設監聽8080
r.Run(":80")
}
3.HTTP伺服器
3.1 GET引數獲取
package main import ( "github.com/gin-gonic/gin" "net/http" ) func getinfos(c *gin.Context) { //獲取name name := c.Query("name") //DefaultQuery 第一個是獲取值 第二個引數是預設值 lastname := c.DefaultQuery("lastname", "這是預設值") c.String(http.StatusOK, "Hello %s,%s", name, lastname) } func main() { r := gin.Default() r.GET("/ping", getinfos) //預設監聽8080 r.Run(":80") }
3.2 POST引數獲取
package main import ( "github.com/gin-gonic/gin" "net/http" ) func postinfos(c *gin.Context) { //獲取name name := c.PostForm("name") //DefaultPostForm 第一個是獲取值 第二個引數是預設值 lastname := c.DefaultPostForm("lastname", "這是預設值") c.String(http.StatusOK, "Hello %s,%s", name, lastname) } func main() { r := gin.Default() r.POST("/postinfos", postinfos) //預設監聽8080 r.Run(":80") }
3.3 JSON引數獲取
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
type Login struct {
Name string `json:"name"`
Password string `json:"password"`
}
func loginJSON(c *gin.Context) {
json := Login{}
//獲取json資料後並解析
if c.BindJSON(&json) == nil {
if json.Name == "root" && json.Password == "root" {
c.JSON(http.StatusOK, gin.H{"status": "登陸成功"})
} else {
c.JSON(http.StatusUnauthorized, gin.H{"status": "賬號或者密碼錯誤"})
}
}
}
func main() {
r := gin.Default()
// 繫結JSON的例子 ({"name": "manu", "password": "123"})
r.POST("/loginJSON", loginJSON)
//預設監聽8080
r.Run(":80")
}
3.4 提交表單獲取引數
package main
import (
"github.com/gin-gonic/gin"
)
type Login struct {
Name string `form:"name"`
Password string `form:"password"`
}
func loginFORM(c *gin.Context) {
form := Login{}
//獲取form資料後並解析
if c.Bind(&form) == nil {
if form.Name == "root" && form.Password == "root" {
c.JSON(200, gin.H{"status": "登陸成功"})
} else {
c.JSON(203, gin.H{"status": "賬號或者密碼錯誤"})
}
}
}
func main() {
r := gin.Default()
r.POST("/loginFORM", loginFORM)
//預設監聽8080
r.Run(":80")
}
3.5 檔案上傳
package main
import (
"github.com/gin-gonic/gin"
"os"
"log"
"io"
"time"
"strconv"
)
//上傳檔案
func file(c *gin.Context) {
//上傳檔名稱
file, header, err := c.Request.FormFile("upload")
if err != nil {
c.JSON(200, gin.H{"msg": "檔案不得為空"})
return
}
filename := time.Now().Unix()
//建立檔案
out, err := os.Create("./public/"+strconv.FormatInt(filename, 10) + ".png")
if err != nil {
log.Fatal(err)
}
defer out.Close()
//複製流檔案
_, err = io.Copy(out, file)
if err != nil {
log.Fatal(err)
}
c.JSON(200, gin.H{"msg": "檔案" + header.Filename + "已經上傳完成,新名字為:" + strconv.FormatInt(filename, 10)})
}
func main() {
r := gin.Default()
r.POST("/file", file)
//預設監聽8080
r.Run(":80")
}
3.6 響應輸出
package main
import (
"github.com/gin-gonic/gin"
)
type msg struct {
Name string
Message string
Number int
}
func moreJSON(c *gin.Context) {
msg := msg{}
msg.Name = "Lena"
msg.Message = "hey"
msg.Number = 123
// 以下方式都會輸出 : {"name": "Lena", "Message": "hey", "Number": 123}
c.JSON(200, gin.H{"Name": "Lena", "Message": "hey", "Number": 123})
c.XML(200, gin.H{"Name": "Lena", "Message": "hey", "Number": 123})
c.YAML(200, gin.H{"Name": "Lena", "Message": "hey", "Number": 123})
//輸出的結構體
c.JSON(200, msg)
c.XML(200, msg)
c.YAML(200, msg)
}
func main() {
r := gin.Default()
r.GET("/moreJSON", moreJSON)
//預設監聽8080
r.Run(":80")
}
3.7 巢狀HTML檢視
3.7.1 HTML簡單輸出
package main
import (
"github.com/gin-gonic/gin"
)
func index(c *gin.Context) {
//根據完整檔名渲染模板,並傳遞引數
c.HTML(200, "live.html", gin.H{
"title": "你就是個二大傻子",
})
}
func main() {
r := gin.Default()
//載入模板
r.LoadHTMLGlob("templates/*")
//定義路由
r.GET("/index", index)
r.Run(":80")
}
live.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>live</title>
</head>
<body>
<h1>11111111111111111</h1>
<h1>{{.title}}</h1>
</body>
</html>
3.7.2 檔案的路由定義
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
//定義多檔案的路徑,使用的是系統的路徑(絕對,相對地址都可以)
r.Static("/a", "D:/phpStudy/WWW/go/templates")
r.Static("/b", "./templates")
r.StaticFS("/c",http.Dir("./templates"))
r.StaticFS("/d",http.Dir("D:/phpStudy/WWW/go/templates"))
//定義單個檔案的路徑,使用的是絕對路徑
r.StaticFile("/e","./templates/live.html")
r.Run(":80")
}
3.7.3 重定向
package main
import (
"github.com/gin-gonic/gin"
)
func redirect_abroad(c *gin.Context) {
//支援外部的重定向
c.Redirect(301, "http://www.baidu.com/")
}
func redirect_within(c *gin.Context) {
//支援內部的重定向
c.Redirect(301, "/home")
}
func index(c *gin.Context) {
c.String(200, "hello world")
}
func home(c *gin.Context) {
c.String(200, "hello home")
}
func main() {
r := gin.Default()
r.GET("/abroad", redirect_abroad)
r.GET("/within", redirect_within)
r.GET("/index", index)
r.GET("/home", home)
r.Run(":80")
}
3.7.4 全域性中介軟體
package main
import (
"github.com/gin-gonic/gin"
)
func index(c *gin.Context) {
c.String(200, "日你大爺的")
}
//中介軟體的定義
func Logger() gin.HandlerFunc {
return func(c *gin.Context) {
name := c.Query("name")
password := c.Query("password")
if name == "admin" && password == "111111" {
c.String(200, "驗證通過</br>")
//請求前
//前置操作
c.Next() //處理請求(只能在中介軟體中使用)
//請求後
//後置操作
c.String(200, "中介軟體過了</br>")
} else {
//資料掛起,打斷
c.Abort()
c.String(200, "我是中介軟體,你沒有許可權")
}
}
}
func main() {
r := gin.Default()
//設定全域性中介軟體
r.Use(Logger())
r.GET("/index", index)
r.Run(":80")
}
3.7.5 分組中介軟體
package main
import (
"github.com/gin-gonic/gin"
)
//中介軟體的定義
func Logger() gin.HandlerFunc {
return func(c *gin.Context) {
name := c.Query("name")
password := c.Query("password")
if name == "admin" && password == "111111" {
c.String(200, "驗證通過</br>")
//請求前
//前置操作
} else {
//資料掛起,打斷
c.Abort()
c.String(200, "我是中介軟體,你沒有許可權")
}
}
}
func index(c *gin.Context) {
c.String(200, "日你大爺的")
}
func home(c *gin.Context) {
c.String(200, "hello home")
}
func login(c *gin.Context) {
c.String(200, "請先登陸!")
}
func main() {
r := gin.Default()
//設定分組中介軟體
s := r.Group("/index", Logger())
{
s.GET("/index", index)
s.GET("/home", home)
}
r.GET("/login", login)
r.Run(":80")
}
3.7.6 設定群組
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func get1(c *gin.Context) {
c.String(http.StatusOK, "Hello get1")
}
func get2(c *gin.Context) {
c.String(http.StatusOK, "Hello get2")
}
func main() {
r := gin.Default()
//設定分組
s := r.Group("/getinfo")
{
s.GET("/get1", get1)
s.GET("/get2", get2)
}
//預設監聽8080
r.Run(":80")
}