本文已参与「新人创作礼」活动,一起开启掘金创作之路。
1、静态服务详解
1、引用静态文件
一个项目,肯定是需要静态文件的,css、js等静态文件应该如何加载呢?!! 就应该使用 r.static()
func main() {
r := gin.Default()
//放在配置路由的上面
r.Static("/static", "./static")
r.LoadHTMLGlob("templates/**/*") //这应该看模板的目录形式,如果是templates文件夹中还有文件夹就使用这种形式。
//否则就使用这种
r.LoadHTMLGlob("templates/*"
//如果是加载html也可以使用
r.LoadHTMLGlob("templates/*.html"
// ...
r.Run(":8080")
}
路由详解
1、GET请求传值
GET : 域名:/index?id=20&page=1
router.GET("/index", func(c *gin.Context) {
id := c.Query("id") //Query获取路径中的值
page := c.DefaultQuery("page", "0") //如果未传值,则使用默认值
c.String(200, "id=%v page=%v", id, page)
})
2、动态路由传值
域名/index/99
r.GET("/index/:id", func(c *gin.Context) {
id := c.Param("id")
c.String(200, "userID=%s", id) })
3、POST请求传值
1、获取form表单数据
{{ define "default/index.html" }} ##渲染模板
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="/indexPost" method="post">
用户名:<input type="text" name="username" />
密码: <input type="password" name="password" />
<input type="submit" value="提交">
</form>
</body>
</html>
{{end}}
2、使用c.PostForm 接收表单传过来的数据
//GET请求渲染页面
router.GET("/index", func(c *gin.Context) {
c.HTML(200, "default/add_user.html", gin.H{
})
})
//POST请求获取页面中form表单中的值
router.POST("/indexPost", func(c *gin.Context) {
username := c.PostForm("username")
password := c.PostForm("password")
age := c.DefaultPostForm("age", "20")
c.JSON(200, gin.H{
"usernmae": username,
"password": password,
"age": age, })
})
3、获取 GET POST 传递的数据绑定到结构体 基于请求的Content-Type识别请求数据类型并利用反射机制自动提取请求中 QueryString、form 表单、JSON、XML 等参数到结构体中。 所以,我一般都是新建一个go文件,里面全是全局变量的结构体(结构体名称首字母大写)
只需在路由实例化一下就好了
router.GET("/", func(c *gin.Context) {
var demandDB DemandDB
//接口
if err := c.ShouldBind(&demandDB); err == nil {
c.JSON(http.StatusOK, demandDB)
} else {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()
})
}
}