网站Logo 90的blog

GIN框架学习

root
7
2024-11-18

一、Gin框架简介与安装

Gin是一个用Go语言编写的Web框架,它以极高的性能和灵活的路由设计著称。安装Gin框架非常简单,只需在终端中运行以下命令:

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

二、响应处理

1. 基础响应类型

字符串响应
package main

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

func main() {
    router := gin.Default()
    router.GET("/index", func(c *gin.Context) {
        c.String(200, "Hello World")
    })
    router.Run(":8080")
}

访问/json路由时,服务器会返回状态码200和JSON格式的用户信息。

XML响应
package main

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

func _xml(c *gin.Context) {
    c.XML(200, gin.H{"user": "ei", "message": "hello", "status": http.StatusOK, "data": gin.H{"user": "lin"}})
}

func main() {
    router := gin.Default()
    router.GET("/xml", _xml)
    router.Run()
}

访问/xml路由时,服务器会返回状态码200和XML格式的数据。

YAML响应
package main

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

func _yaml(c *gin.Context) {
    c.YAML(200, gin.H{"user": "ei", "message": "hello", "status": http.StatusOK, "data": gin.H{"user": "lin"}})
}

func main() {
    router := gin.Default()
    router.GET("/yaml", _yaml)
    router.Run()
}
HTML响应
package main

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

type User struct {
    Username string `json:"user_name"`
    Age      int    `json:"Age"`
    Password string `json:"-"` // 忽略该字段
}

func _html(c *gin.Context) {
    user := User{"ei", 18, "123456"}
    c.HTML(200, "index.html", user)
}

func main() {
    router := gin.Default()
    router.LoadHTMLGlob("templates/*")
    router.GET("/html", _html)
    router.Run()
}

2. 文件响应

router.LoadHTMLGlob("templates/*")
router.StaticFS("/static", http.Dir("static/static"))
router.StaticFile("/img.png", "static/img.png")

3. 重定向

func _redirect(c *gin.Context) {
    c.Redirect(301, "https://www.baidu.com")
}

动物装饰