go学习01

加载网页文件夹和加载静态资源

文件路径:

    <link rel="stylesheet" href="/static/css/style.css">
    <script src="/static/js/common.js"></script>
    //加载网页文件夹
    ginServer.LoadHTMLGlob("templates/*")
    //加载静态资源
    ginServer.Static("/static", "./static")

获取静态页面

	ginServer.GET("/index", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.html", gin.H{
			"msg": "后台数据",
		})
	})

index.html中获取msg的代码为

{{.msg}}

返回URL参数的两种方式

1.使用?传递参数,如/user/info?userid=123&username=JohnDoe

	ginServer.GET("/user/info", func(c *gin.Context) {
		userid := c.Query("userid")
		username := c.Query("username")
		c.JSON(http.StatusOK, gin.H{
			"userid":   userid,
			"username": username,
		})
	})

2.使用路由路径传递参数,如/user/info/123/JohnDoe

	ginServer.GET("/user/info/:userid/:username", func(c *gin.Context) {
		userid := c.Param("userid")
		username := c.Param("username")
		c.JSON(http.StatusOK, gin.H{
			"userid":   userid,
			"username": username,
		})
	})

表单提交数据

表单

<form action="/user/add" method="post">
    <p>username: <input type="text" name="username"></p>
    <p>password: <input type="text" name="password"></p>
    <button type="submit">提交</button>
</form>
	ginServer.POST("/user/add", func(c *gin.Context) {
		username := c.PostForm("username")
		password := c.PostForm("password")
		c.JSON(http.StatusOK, gin.H{
			"username": username,
			"password": password,
		})
	})

重定向

	ginServer.GET("/text", func(c *gin.Context) {
		c.Redirect(http.StatusMovedPermanently, "https://www.baidu.com")
	})

接受post请求的数据并以json的格式响应

	ginServer.POST("/json", func(c *gin.Context) {
		b, _ := c.GetRawData()
		var m map[string]interface{}
		_ = json.Unmarshal(b, &m)
		c.JSON(http.StatusOK, m)
	})

请求格式与响应结果

posted @ 2024-04-30 11:23  wushucan  阅读(8)  评论(0)    收藏  举报