Golang的Gin框架
Gin是一个用Go语言编写的web框架,它以简单且高效的方式编写web应用。以下是一些使用Gin框架的示例。
- 基本的GET路由处理:
package main
import "github.com/gin-gonic/gin"
func main() {
r := gin.Default()
r.GET("/", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "Hello world!",
})
})
r.Run()
}
- 使用Gin的路由组:
package main
import "github.com/gin-gonic/gin"
func main() {
r := gin.Default()
v1 := r.Group("/v1")
{
v1.GET("/hello", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "Hello from v1!",
})
})
}
v2 := r.Group("/v2")
{
v2.GET("/hello", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "Hello from v2!",
})
})
}
r.Run()
}
- 使用Gin的中间件:
package main
import "github.com/gin-gonic/gin"
func main() {
r := gin.Default()
// Middleware
Authorized := r.Group("/")
Authorized.Use(AuthMiddleware())
{
Authorized.GET("content", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "Content!",
})
})
}
r.Run()
}
func AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
// 你的认证逻辑
auth := c.MustGet("Auth").(string)
if auth != "Some secret" {
c.Abort()
c.JSON(401, gin.H{"error": "Unauthorized"})
return
}
c.Next()
}
}
- 使用Gin的JSON绑定和验证:
package main
import (
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
)
type RegisterRequest struct {
Username string `json:"username" binding:"required"`
Password string `json:"password" binding:"required"`
Email string `json:"email" binding:"required,email"`
}
func main() {
r := gin.Default()
r.POST("/register", func(c *gin.Context) {
var r RegisterRequest
if err := c.ShouldBindWith(&r, binding.JSON); err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
评论已关闭