gin
1.helloworld
package main
import "github.com/gin-gonic/gin"
func main() {
engine := gin.Default()
engine.GET("/hello", func(context *gin.Context) {
context.Writer.Write([]byte("hello"))
})
engine.Run(":8090")
}
使用handle处理请求
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"log"
)
func main() {
engine := gin.Default()
engine.Handle("GET", "/hello", func(context *gin.Context) {
fmt.Println(context.FullPath())
fmt.Println(context.Request.URL)
fmt.Println(context.Request.Method)
context.Writer.WriteString("hello world")
})
// 获取GET请求 http://127.0.0.1:8090/demo?name=wanghaha&age=24
engine.Handle("GET", "/demo", func(context *gin.Context) {
fmt.Println(context.FullPath())
name := context.DefaultQuery("name", "wang")
age := context.Query("age")
fmt.Println(name, age)
context.Writer.WriteString(fmt.Sprintf("name:%v, age:%v", name, age))
})
// 获取POST请求
engine.Handle("POST", "/demoPost", func(context *gin.Context) {
fmt.Println(context.FullPath())
username := context.PostForm("username")
password := context.PostForm("password")
fmt.Println("username:", username)
fmt.Println("password:", password)
context.Writer.WriteString(fmt.Sprintf("username: %v, password: %v", username, password))
})
err := engine.Run(":8090")
if err != nil {
log.Fatal(err)
}
}
直接使用gin封装后的GET, POST, DELETE等
package main
import "github.com/gin-gonic/gin"
func main() {
engine := gin.Default()
engine.GET("/hello", func(context *gin.Context) {
name := context.Query("name")
context.Writer.WriteString(name)
})
engine.POST("/login", func(context *gin.Context) {
username := context.PostForm("username")
password := context.PostForm("password")
if username == "admin" && password == "111111" {
context.Writer.WriteString("ok")
} else {
context.Writer.WriteString("username or password error")
}
})
engine.DELETE("/delete_user/:id", func(context *gin.Context) {
id := context.Param("id")
context.Writer.WriteString(id)
})
engine.Run(":8090")
}
参数绑定 GET请求
http://127.0.0.1:8090/hello?name=wanghaha&age=24&sex=1
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"log"
)
func main() {
engine := gin.Default()
// 参数绑定GET请求
engine.GET("/hello", func(context *gin.Context) {
var user User
err := context.ShouldBindQuery(&user)
if err != nil {
log.Fatal(err)
}
fmt.Println(user.Name)
fmt.Println(user.Age)
fmt.Println(user.Sex)
context.Writer.WriteString(user.Name)
})
err := engine.Run(":8090")
if err != nil {
log.Fatal(err)
}
}
type User struct{
Name string `form:"name"`
Age int `form:"age"`
Sex int `form:"sex"`
}
参数绑定 POST请求
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"log"
)
func main() {
engine := gin.Default()
// 参数绑定POST请求
engine.POST("/testPost", func(context *gin.Context) {
var user User
err := context.ShouldBind(&user)
if err != nil {
log.Fatal(err)
}
fmt.Println(user.Name)
fmt.Println(user.Age)
fmt.Println(user.Sex)
context.Writer.WriteString(user.Name)
})
err := engine.Run(":8090")
if err != nil {
log.Fatal(err)
}
}
type User struct{
Name string `form:"name"`
Age int `form:"age"`
Sex int `form:"sex"`
}
绑定JSON格式数据
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"log"
)
func main() {
engine := gin.Default()
// 参数绑定POST, JSON格式请求
engine.POST("/testPost", func(context *gin.Context) {
var user User
err := context.BindJSON(&user)
if err != nil {
log.Fatal(err)
}
fmt.Println(user.Name)
fmt.Println(user.Age)
fmt.Println(user.Sex)
context.Writer.WriteString(user.Name)
})
err := engine.Run(":8090")
if err != nil {
log.Fatal(err)
}
}
type User struct{
Name string `form:"name"`
Age int `form:"age"`
Sex int `form:"sex"`
}
返回JSON数据
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
engine := gin.Default()
// 返回JSON格式数据,第一种方式
engine.GET("/", func(context *gin.Context) {
context.JSON(200, map[string]interface{}{
"code": 0,
"msg": "ok",
"data": map[string]interface{}{
"value": 25,
},
})
})
// 返回JSON格式数据,第二种方式
engine.GET("/t1", func(context *gin.Context) {
context.JSON(http.StatusOK, gin.H{
"code": 0,
"msg": "ok",
})
})
// 返回JSON格式数据,第三种方式
engine.GET("/t2", func(context *gin.Context) {
context.JSON(200, Response{
Code: 0,
Msg: "ok",
Data: nil,
})
})
engine.Run(":8090")
}
// 自定义响应结构体
type Response struct{
Code int
Msg string
Data interface{}
}
返回html&加载静态文件
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
engine := gin.Default()
// 加载模板文件
engine.LoadHTMLGlob("./templates/*")
// 加载静态文件目录
engine.Static("/static", "./static")
engine.GET("/", func(context *gin.Context) {
context.HTML(200, "index.html", nil)
})
engine.GET("/home", func(context *gin.Context) {
context.HTML(http.StatusOK, "home.html", gin.H{
"title": "home page",
"message": "hello world",
})
})
engine.Run(":8090")
}
templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
<h1>index page</h1>
<img src="/static/feng.jpg" alt="">
</body>
</html>
templates/home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{.title}}</title>
</head>
<body>
<h1>message: {{.message}}</h1>
</body>
</html>
路由组
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"log"
"net/http"
)
func main() {
engine := gin.Default()
// 路由分组
api := engine.Group("/api")
// 获取用户接口
api.GET("/get_user/:id", func(context *gin.Context) {
context.JSON(http.StatusOK, gin.H{"id": context.Param("id")})
})
// 添加用户接口
api.POST("/add_user", func(context *gin.Context) {
type User struct {
Name string `form:"name"`
Age int `form:"age"`
}
var user User
if err := context.ShouldBind(&user); err != nil {
log.Fatal(err)
}
fmt.Printf("name: %v, age:%v\n", user.Name, user.Age)
context.JSON(http.StatusOK, gin.H{
"code": 0,
"msg": "ok",
})
})
// 删除用户接口
api.DELETE("/delete_user/:id", func(context *gin.Context) {
context.JSON(http.StatusOK, gin.H{"id": context.Param("id")})
})
if err := engine.Run(":8090"); err != nil {
log.Fatal(err)
}
}
试图函数另一种写法
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"log"
"net/http"
)
func main() {
engine := gin.Default()
// 路由分组
api := engine.Group("/api")
{
// 获取用户接口
api.GET("/get_user/:id", GetUser)
// 添加用户接口
api.POST("/add_user", AddUser)
// 删除用户接口
api.DELETE("/delete_user/:id", DeleteUser)
}
if err := engine.Run(":8090"); err != nil {
log.Fatal(err)
}
}
// 获取用户
func GetUser(context *gin.Context) {
context.JSON(http.StatusOK, gin.H{"id": context.Param("id")})
}
// 添加用户
func AddUser(context *gin.Context) {
type User struct {
Name string `form:"name"`
Age int `form:"age"`
}
var user User
if err := context.ShouldBind(&user); err != nil {
log.Fatal(err)
}
fmt.Printf("name: %v, age:%v\n", user.Name, user.Age)
context.JSON(http.StatusOK, gin.H{
"code": 0,
"msg": "ok",
})
}
// 删除用户
func DeleteUser(context *gin.Context) {
context.JSON(http.StatusOK, gin.H{"id": context.Param("id")})
}
中间件
全局使用中间件
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"log"
"net/http"
)
func main() {
engine := gin.Default()
// 全局使用该中间件
engine.Use(MiddlewareDemo())
engine.GET("/hello", func(context *gin.Context) {
context.String(http.StatusOK, "hello")
})
engine.GET("/test", func(context *gin.Context) {
context.String(http.StatusOK, "test")
})
if err := engine.Run(":8090"); err != nil {
log.Fatal(err)
}
}
// 自定义中间件
func MiddlewareDemo() gin.HandlerFunc {
return func(context *gin.Context) {
fmt.Println(context.Request.URL)
fmt.Println(context.Request.RequestURI)
fmt.Println(context.FullPath())
fmt.Println(context.Request.Host)
fmt.Println(context.Request.UserAgent())
}
}
某一个视图函数使用中间件
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"log"
"net/http"
)
func main() {
engine := gin.Default()
// 局部使用中间件
engine.GET("/hello",MiddlewareDemo(), func(context *gin.Context) {
context.String(http.StatusOK, "hello")
})
engine.GET("/test", func(context *gin.Context) {
context.String(http.StatusOK, "test")
})
if err := engine.Run(":8090"); err != nil {
log.Fatal(err)
}
}
// 自定义中间件
func MiddlewareDemo() gin.HandlerFunc {
return func(context *gin.Context) {
fmt.Println(context.Request.URL)
fmt.Println(context.Request.RequestURI)
fmt.Println(context.FullPath())
fmt.Println(context.Request.Host)
fmt.Println(context.Request.UserAgent())
}
}
中间件next
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"log"
"net/http"
)
func main() {
engine := gin.Default()
// 局部使用中间件
engine.GET("/hello",MiddlewareDemo(), func(context *gin.Context) {
fmt.Println("我在执行业务代码")
context.String(http.StatusOK, "hello")
})
engine.GET("/test", func(context *gin.Context) {
context.String(http.StatusOK, "test")
})
if err := engine.Run(":8090"); err != nil {
log.Fatal(err)
}
}
// 自定义中间件
func MiddlewareDemo() gin.HandlerFunc {
return func(context *gin.Context) {
fmt.Println(context.Request.URL)
fmt.Println(context.Request.RequestURI)
fmt.Println(context.FullPath())
fmt.Println(context.Request.Host)
fmt.Println(context.Request.UserAgent())
// 执行到next的时候会去执行业务代码
context.Next()
fmt.Println("我是视图函数执行结束了后执行的")
}
}