Go學習筆記二——windows下使用Gin


Gin 是一個用 Go (Golang) 編寫的 web 框架

它具有運行速度快,分組的路由器,良好的崩潰捕獲和錯誤處理,非常好的支持中間件和 json

go的版本

配置環境變量

set GO111MODULE=on
set GOPROXY=https://goproxy.io

初始化

go mod init  demo

獲取Gin

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

1.簡單例子

入口文件main.go

package main

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

func main() {
    r := gin.Default()
    r.GET("/test", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "message": "hello",
        })
    })
    r.Run() // listen and serve on 0.0.0.0:8080
}

運行

go run main.go

瀏覽器訪問http://localhost:8080/test

返回

{"message":"hello"}

Gin是一個輕量級的 WEB 框架

  支持 RestFull 風格 API,支持 GET,POST,PUT,PATCH,DELETE,OPTIONS 等 http 方法,支持文件上傳,分組路由,Multipart/Urlencoded FORM,支持 JsonP,參數處理

2.修改啟動方式

默認啟動方式,包含 Logger、Recovery 中間件

r := gin.Default()

請求接口會輸出日志

無中間件啟動

r := gin.New()

 請求接口不再輸出日志

3.日志寫入文件

package main

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

func main() {

    gin.DisableConsoleColor()

    // 創建記錄日志的文件
    f, _ := os.Create("gin.log")
    gin.DefaultWriter = io.MultiWriter(f)
    // 如果需要將日志同時寫入文件和控制台,請使用以下代碼
    // gin.DefaultWriter = io.MultiWriter(f, os.Stdout)
    r := gin.Default()

    r.GET("/test", func(c *gin.Context) {
        c.JSON(http.StatusOK, gin.H{
            "message": "hello",
        })
    })
    r.Run() // listen and serve on 0.0.0.0:8080
}

啟動

以前輸出的都寫入和main.go在同一目錄下的gin.log中

4.靜態資源

  StaticFile 是加載單個文件

  StaticFS 是加載一個完整的目錄資源

package main

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

func main() {
    r := gin.Default()
    r.StaticFS("/public", http.Dir("E:/go_projects/demo/static"))
    r.StaticFile("/favicon.ico", "./favicon.ico")
    r.Run() // listen and serve on 0.0.0.0:8080
}

5.上傳文件

  單文件

package main

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

func main() {
    r := gin.Default()
    r.StaticFS("/public", http.Dir("E:/go_projects/demo/static"))
    r.GET("/test", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "message": "hello",
        })
    })
    r.POST("/upload", func(c *gin.Context) {
        // 單文件
        file, _ := c.FormFile("file")
        log.Println(file.Filename)
        dst := path.Join("./static/upload", file.Filename)
        // 上傳文件至指定目錄
        c.SaveUploadedFile(file, dst)
        c.JSON(200, gin.H{
            "message": file.Filename+" uploaded!",
        })
    })
    r.Run() // listen and serve on 0.0.0.0:8080
}

測試

  多文件

package main

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

func main() {
    r := gin.Default()
    r.StaticFS("/public", http.Dir("E:/go_projects/demo/static"))
    r.GET("/test", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "message": "hello",
        })
    })

    r.POST("/upload", func(c *gin.Context) {
        // 多文件
        form, _ := c.MultipartForm()
        files := form.File["files[]"]

        for _, file := range files {
            log.Println(file.Filename)
            dst := path.Join("./static/upload", file.Filename)
            // 上傳文件至指定目錄
            c.SaveUploadedFile(file, dst)
        }

        c.JSON(200, gin.H{
            "message":  strconv.Itoa(len(files))+" uploaded!",
        })
    })
    r.Run() // listen and serve on 0.0.0.0:8080
}

測試

6.獲取參數

(1)獲取路徑中的參數

package main

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

func main() {

    r := gin.Default()

    r.StaticFS("/public", http.Dir("E:/go_projects/demo/static"))

    r.GET("/test/:firstname/:lastname", func(c *gin.Context) {
        firstname := c.Param("firstname")
        lastname := c.Param("lastname")
        c.JSON(http.StatusOK, gin.H{
            "message": "hello",
            "firstname":firstname,
            "lastname":lastname,
        })
    })
    r.Run() // listen and serve on 0.0.0.0:8080
}

測試

(2)獲取GET參數

c.Query 解析?后的參數,eg: key1=value2&key2=value2

c.DefaultQuery 處理默認參數

package main

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

func main() {

    r := gin.Default()

    r.GET("/test", func(c *gin.Context) {
        firstname := c.DefaultQuery("firstname", "Guest")
        lastname := c.Query("lastname")
        c.JSON(http.StatusOK, gin.H{
            "message": "hello",
            "firstname":firstname,
            "lastname":lastname,
        })
    })
    r.Run() // listen and serve on 0.0.0.0:8080
}

測試

(3)獲取post參數

c.PostFROM 解析的是  x-www-form-urlencoded 或 from-data 的參數

c.DefaultPostForm 處理默認參數

package main

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

func main() {

    r := gin.Default()

    r.StaticFS("/public", http.Dir("E:/go_projects/demo/static"))

    r.POST("/test", func(c *gin.Context) {
        firstname := c.DefaultPostForm("firstname", "Guest")
        lastname :=  c.PostForm("lastname")
        c.JSON(http.StatusOK, gin.H{
            "message": "hello",
            "firstname":firstname,
            "lastname":lastname,
        })
    })
    r.Run() // listen and serve on 0.0.0.0:8080
}

測試

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM