golang的web框架Gin(二)---Gin的Resutful风格

Restful风格是什么?

REST与技术无关,代表的是一种软件架构风格,REST是Representational State Transfer的简称,中文翻译为“表征状态转移”或“表现层状态转化”。

RESTFUL特点包括:

  1. 每一个URI代表1种资源;
  2. 客户端使用GET、POST、PUT、DELETE4个表示操作方式的动词对服务端资源进行操作:GET用来获取资源,POST用来新建资源(也可以用于更新资源),PUT用来更新资源,DELETE用来删除资源
  3. 通过操作资源的表现形式来操作资源;
  4. 资源的表现形式是XML或者HTML;
  5. 客户端与服务端之间的交互在请求之间是无状态的,从客户端到服务端的每个请求都必须包含理解请求所必需的信息。

简单来说,REST的含义就是客户端与Web服务器之间进行交互的时候,使用HTTP协议中的4个请求方法代表不同的动作。

接收前端传递过来的参数

querystring指的是URL中?后面携带的参数,

例如:url?userid=xxx&username=zs。 获取请求的querystring参数的方法如下:

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

获取path参数

请求的参数通过URL路径传递,例如://url/info?userid/username。 获取请求URL路径中的参数的方式如下。

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

获取json参数

当前端请求的数据通过JSON提交时,例如向/json发送一个POST请求,则获取请求参数的方式如下:

//接收json
	ginServer.GET("/json", func(context *gin.Context) {
    
    
		//request.body
		//[]byte
		b, _ := context.GetRawData() // 从c.Request.Body读取请求数据
		var m map[string]interface{
    
    }
		//包装为json数据 []byte 反序列化
		_ = json.Unmarshal(b, &m)
		context.JSON(http.StatusOK, m)
	})

接收表单数据

当前端请求的数据通过form表单提交时,例如向/user/add发送一个POST请求,获取请求数据的方式如下:

form 表单

<form action="/user/add" method="post">
    <p>username: <input type="text" name="username"></p>
    <p>password: <input type="password" name="password"></p>
    <button type="submit"> 提交 </button>
</form>

接口

//接收表单数据
	ginServer.POST("/user/add", func(context *gin.Context) {
    
    
		username := context.PostForm("username")
		password := context.PostForm("password")
		context.JSON(http.StatusOK, gin.H{
    
    
			"msg":      "ok",
			"username": username,
			"password": password,
		})
	})

路由

重定向

	//路由
	ginServer.GET("/test", func(context *gin.Context) {
    
    
		//重定向 301
		// StatusPermanentRedirect 永久重定向
		// StatusTemporaryRedirect 暂时重定向
		context.Redirect(http.StatusPermanentRedirect, "https://www.bing.com")
	})

404 NoRoute

	ginServer.NoRoute(func(context *gin.Context) {
    
    
		context.HTML(http.StatusNotFound, "404.html", nil)
	})

加载静态页面

html、css、js
在这里插入图片描述
代码

	//加载静态页面
	ginServer.LoadHTMLGlob("templates/*")
	//ginServer.LoadHTMLFiles("templates/index.html")

	//加载资源文件
	ginServer.Static("/static", "./static")

	//响应一个页面给前端
	ginServer.GET("/index", func(context *gin.Context) {
    
    
		//context.JSON() json 数据
		context.HTML(http.StatusOK, "index.html", gin.H{
    
    
			"msg": "这是一个数据",
		})
	})

猜你喜欢

转载自blog.csdn.net/m0_49683806/article/details/128998317