一、
1.安装
go get -u github.com/gin-gonic/gin
2.例子
package main
import "github.com/gin-gonic/gin"
func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
r.Run()
}
3.测试
http://127.0.0.1:8080/ping
4.结合 vue和Bootstrap
main.go
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.LoadHTMLGlob("view/*")
r.GET("/", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.html", gin.H{})
})
r.Run()
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" >
</head>
<body>
<div id="vm" class="container">
<div class="d-flex justify-content-center p-5">
<input v-model="message"/>
</div>
<div class="d-flex justify-content-center">
<h1>${message}</h1>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" ></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" ></script>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
var vm = new Vue({
// 由于双花括号和go模板冲突,把vue双花改成${message}形式
delimiters: ['${', '}'],
el: '#vm',
data: {
message: null
}
})
</script>
</body>
</html>
二、
1.请求方式及请求路径
func main() {
//使用默认中间件创建一个gin路由器
r := gin.Default()
//get请求方式:参数1地址,参数2函数
r.GET("/", getting)
//启动默认端口8080
r.Run()
}
func getting(c *gin.Context) {
//
c.JSON(200, "Hello")
}
2.参数
(1)路径传参
127.0.0.1:8080/tom
func main() {
r := gin.Default()
//get请求方式:参数1地址,参数2函数
r.GET("/:name", getting)
r.Run()
}
func getting(c *gin.Context) {
//
name := c.Param("name")
c.String(200, "Hello %s", name)
}
(2)get
func main() {
r := gin.Default()
r.GET("/", getting)
r.Run()
}
func getting(c *gin.Context) {
//设置默认值,如果客户端为传递str1,则默认赋值为def
str1 := c.DefaultQuery("str1", "def")
str2 := c.Query("str2") // 是 c.Request.URL.Query().Get("str2") 的简写
c.String(200, "Hello %s\n", str1)
c.String(200, "Hello %s", str2)
}
(3)表单
func main() {
r := gin.Default()
r.POST("/", posting)
r.Run()
}
func posting(c *gin.Context) {
name := c.PostForm("name")
c.String(200, "Hello %s \n", name)
age := c.DefaultPostForm("age", "18") // 此方法可以设置默认值
c.String(200, "Hello %s", age)
}