zoukankan      html  css  js  c++  java
  • gin学习笔记--模板渲染与获取参数

    gin学习笔记--模板渲染与获取参数

    废话不说,先上代码

    目录结构:

    mark

    说明:

    • [x] 主程序main.go
    • [x] template文件夹下放置两个html模板文件
    • [x] static文件夹下防止静态文件,这里放的是一张图片,用于后面静态文件加

    源码:

    main.go:

    
    package main
    import (
    	"github.com/gin-gonic/gin"
    	"net/http"
    )
    func loginHandle(c *gin.Context){
    	//渲染模板,已经解析好的模板里填充字段
    	c.HTML(http.StatusOK,"login.html",gin.H{
    		"msg":"我爱你",
    	})
    }
    func indexHandle(c *gin.Context){
    	//渲染
    	c.HTML(http.StatusOK,"index.html",gin.H{
    		"msg":"快滚",
    	})
    }
    //json渲染
    func jsonHandle(c *gin.Context){
    
    	var user struct{
    		Name string`json:"user"`
    		Id int
    		Age int
    	}
    	user.Name="zhouzheng"
    	user.Age=24
    	user.Id=1
    
    	c.JSON(200,user)
    }
    //yaml渲染
    func yamlHandle(c *gin.Context){
    	c.YAML(http.StatusOK, gin.H{"message": "ok", "status": http.StatusOK})
    }
    //query-string提取
    func queryHandle(c *gin.Context)	{
    	//拿到请求行里的query-string信息
    	firstname := c.DefaultQuery("firstname", "Guest")//设置默认值
    	lastname := c.Query("lastname")
    	c.String(http.StatusOK, "Hello %s %s", firstname, lastname)
    }
    //form信息提取
    func formHandle(c *gin.Context){
    	//拿到form表单信息,原生的里是用r.Form得到
    	// DefaultPostForm取不到值时会返回指定的默认值
    	//username := c.DefaultPostForm("username", "小王子")
    	username := c.PostForm("username")
    	address := c.DefaultQuery("addresss","beijing")//设置默认值
    	//输出json结果给调用方(渲染)
    	c.JSON(http.StatusOK, gin.H{
    		"status":gin.H{//又内嵌了一个结构体
    			"id":10,
    		},
    		"message":  "ok",
    		"username": username,
    		"address":  address,
    	})
    }
    //提取path参数
    func pathHandle(c *gin.Context){
    	//Param returns the value of the URL param.解析路径=参数
    	username:=c.Param("username")
    	lastname:=c.Param("lastname")
    	//渲染并发送
    	c.JSON(200,gin.H{
    		"username":username,
    		"lastname":lastname,
    	})
    }
    func main(){
    	// 创建一个默认的路由引擎
    	r := gin.Default()
    	//加载模板文件,等价于template里面的template.ParseFiles()
        //r.LoadHTMLFiles("templates/posts/index.html", "templates/users/index.html")
    	r.LoadHTMLGlob("template/*")
    	//则会之静态文件目录
    	//第一参数=是代码里使用的路径,第二个路径是真正你静态文件的路径
    	r.Static("/dsb","./static")//就是做了个路径的替换
    	r.GET("/login",loginHandle)
    	r.GET("/index",indexHandle)
    	r.GET("/json",jsonHandle)
    	r.GET("/yaml", yamlHandle)
    	r.GET("/welcome", queryHandle )
    	r.POST("/form", formHandle )
    	r.GET("/user/search/:username/:address", pathHandle )
    	r.Run()
    }
    

    index.html:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>index</title>
    </head>
    <body>
        <h1>  index</h1>
        <div> {{.msg}}</div>
    <img src="/dsb/image/ycy.jpg" alt=" ">  //用静态文件嵌入了一张图片
    </body>
    </html>
    

    login.html:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>login</title>
    </head>
    <body>
        <h1>  login</h1>
        <div> {{.msg}}</div>
    </body>
    </html>
    

    代码讲解:

    1. html渲染

      首先看html渲染部分,Gin框架中使用LoadHTMLGlob()或者LoadHTMLFiles()方法进行HTML模板渲染。

      r.LoadHTMLGlob("template/*")代表解析template目录下所有模板。等价于r.LoadHTMLFiles("templates/posts/index.html", "templates/users/index.html")

    2. json和yaml渲染

      json和yaml渲染没啥好说的,分别调用c.Json()c.Yaml()即可。

      这里c.Json()渲染有两种方法,一种是直接传一个结构体进去,像上文c.JSON(200,user),也可以在函数里使用gin.H拼接,例如c.JSON(http.StatusOK, gin.H{"message": "Hello world!"})

    3. query-string 获取

      query string参数与body参数

      web提供的服务通常是client和server的交互。其中客户端向服务器发送请求,除了路由参数,其他的参数无非两种,查询字符串query string和报文体body参数。所谓query string,即路由用,用?以后连接的key1=value2&key2=value2的形式的参数。当然这个key-value是经过urlencode编码。

      这里我理解为当使用GET方法时,query-string是放在url中的内容,当使用POST时,信息由form表单提交,键值对信息存储在请求体body中。

      query string

      对于参数的处理,经常会出现参数不存在的情况,对于是否提供默认值,gin也考虑了,并且给出了一个优雅的方案:使用c.DefaultQuery方法读取参数,其中当参数不存在的时候,提供一个默认值;使用Query方法读取正常参数,当参数不存在的时候,返回空字串。

      body

      http的报文体传输数据就比query string稍微复杂一点,常见的格式就有四种。例如application/jsonapplication/x-www-form-urlencoded, application/xmlmultipart/form-data。后面一个主要用于图片上传。json格式的很好理解,urlencode其实也不难,无非就是把query string的内容,放到了body体里,同样也需要urlencode。默认情况下,c.PostFROM解析的是x-www-form-urlencodedfrom-data的参数。

      与get处理query参数一样,post方法也提供了处理默认参数的情况。同理,如果参数不存在,将会得到空字串。

      本段参考内容:https://www.jianshu.com/p/a31e4ee25305

    4. path参数提取

      这里不是很明白。

    5. 静态文件处理

      核心函数r.Static("/dsb","./static"),与index.html里的<img src="/dsb/image/ycy.jpg" alt=" ">对应。

    调试结果:

    1. 主程序运行

    mark

    1. 使用postman进行测试

    mark

    image-20200528010113938

    mark

    mark

    mark

    mark

    推荐阅读:

    gin框架介绍和使用

    Golang 微框架 Gin 简介

    golang轻量级框架-Gin入门

  • 相关阅读:
    [NOI2003][bzoj1507] 文本编辑器 editor [splay]
    GDKOI 游记
    [填坑完毕] 寒假作业计划
    省选算法学习-数据结构-splay
    NOIP2017游记
    真·总结
    赛前
    十一黄(xun)金(lian)周感想
    9.17 模拟赛
    9.14 模拟赛
  • 原文地址:https://www.cnblogs.com/wind-zhou/p/12977786.html
Copyright © 2011-2022 走看看