GoWeb -- gin框架的入门和使用(2)

这篇具有很好参考价值的文章主要介绍了GoWeb -- gin框架的入门和使用(2)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

前言

书接上回,在gin的框架使用中,还有着许多方法以及它们的作用,本篇博客将会接着上次的内容继续记录本人在学习gin框架时的思路和笔记。
如果还没有看过上篇博客的可以点此跳转。

map参数

请求url: http://localhost:8080/user/save?addressMap[home]=Beijing&addressMap[company]=shanghai

	//map形式获取参数
	r.GET("/user/save", func(context *gin.Context) {
		addressMap := context.QueryMap("addressMap")
		context.JSON(200, addressMap)
	})

一般我们使用context.QueryMap方法来获取map类型的参数。

GoWeb -- gin框架的入门和使用(2)

Post请求参数

post请求一般是表单参数和json参数

表单参数

	r.POST("/user/save", func(context *gin.Context) {
		username := context.PostForm("username")
		password := context.PostForm("password")

		context.JSON(200, gin.H{
			username: username,
			password: password,
		})
	})

一般使用context.PostForm获取表单元素对应value的值

这里简单写了一个表单界面

<!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="http://localhost:8080/user/save" method="post">
        name:<input type="text" name="username">
        password:<input type="text" name="password">
        <input type="submit" value="提交">
    </form>

</body>

</html>

GoWeb -- gin框架的入门和使用(2)
是这个样子的,分别填写内容并点击提交

GoWeb -- gin框架的入门和使用(2)
GoWeb -- gin框架的入门和使用(2)
服务器就会接收这两个参数并返回

json参数

json参数形如:

{
	"id":1111,
	"name":"张三",
	"address":[
		"beijing",
		"shanghai"
		]
}
//获取json参数
	r.POST("/user/json", func(context *gin.Context) {
		var user User
		context.ShouldBindJSON(&user)
		context.JSON(200,user)
	})

路径参数

请求url:http://localhost:8080/user/save/111

//获取路径参数
	r.GET("/user/save/:id/:name", func(context *gin.Context) {
		id := context.Param("id")
		name := context.Param("name")
		context.JSON(200, gin.H{
			"id":   id,
			"name": name,
		})
	})

GoWeb -- gin框架的入门和使用(2)

第二种 方法


type User struct {
	Id      int64    `form:"id" uri:"id"'`
	Name    string   `form:"name" uri:"name"`
	Address []string `form:"address"`
}

	//获取路径参数
	r.GET("/user/save/:id/:name", func(context *gin.Context) {
		var user User
		context.ShouldBindUri(&user)
		//id := context.Param("id")
		//name := context.Param("name")
		context.JSON(200, user)
	})

GoWeb -- gin框架的入门和使用(2)

文件参数

	//获取文件参数
	r.POST("/user/file", func(context *gin.Context) {
		form, err := context.MultipartForm()
		if err != nil {
			log.Println(err)
		}

		value := form.Value
		files := form.File
		for _, fileArray := range files {
			for _, v := range fileArray {
				context.SaveUploadedFile(v, "./"+v.Filename)
			}
		}

		context.JSON(200, value)
	})

我们一般使用form, err := context.MultipartForm()获取文件
form.Value是文件的值
form.File是整个文件
context.SaveUploadedFile可以把文件储存在本地

响应

响应就是客服端把请求发过来的时候我们给客户端响应信息的数据
响应的方式可以有很多种

返回字符串的形式

	r.GET("/get/response", func(context *gin.Context) {
		context.String(200, "this is %s", "response string")
	})

GoWeb -- gin框架的入门和使用(2)

返回json方式

	//返回json形式
	r.GET("/get/json", func(context *gin.Context) {
		context.JSON(200,gin.H{
			"xxx":"xxx",
		})
	})

模板渲染

模板是golang语言的一个标准库,使用场景很多,gin框架同样支持模板

基本使用

定义一个存放模板文件的templates文件夹
并新建index.html

GoWeb -- gin框架的入门和使用(2)
在index.html下写入

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Title</title>
</head>
<body>
{{.title}}
</body>
</html>

后端:

	//加载模板
	r.LoadHTMLFiles("./templates/index.html")
	r.GET("/index", func(context *gin.Context) {
		context.HTML(200, "index.html", gin.H{
			"title": "hello",
		})
	})

服务器启动后访问localhost:8080/index

GoWeb -- gin框架的入门和使用(2)

多个模板渲染

	//加载模板
	r.LoadHTMLGlob("./template/**")
	//r.LoadHTMLFiles("./templates/index.html", "./remplates/user.html")
	r.GET("/index", func(context *gin.Context) {
		context.HTML(200, "index.html", gin.H{
			"title": "hello",
		})
	})
	r.GET("user", func(context *gin.Context) {
		context.HTML(200, "index.html", gin.H{
			"title": "hello user",
		})
	})

多模板渲染一般使用r.LoadHTMLGlob(“./template/**”)

自定义模板函数

	//自定义模板函数
	r.SetFuncMap(template.FuncMap{
		"safe":func(str string) template.HTML{
			return template.HTML(str)
		},

	})

	//加载模板
	r.LoadHTMLGlob("./template/**")
	//r.LoadHTMLFiles("./templates/index.html", "./remplates/user.html")
	r.GET("/index", func(context *gin.Context) {
		context.HTML(200, "index.html", gin.H{
			"title": "<a href='www.baidu.com'>hello</a>",
		})
	})

前端:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Title</title>
</head>
<body>
{{.title | safe}}
</body>
</html>

GoWeb -- gin框架的入门和使用(2)

静态文件处理

如果在模板中引入静态文件,比如样式文件
index.css

	//引入静态文件
	r.Static("/css", "./static/css")

GoWeb -- gin框架的入门和使用(2)
index.css:

body{
    font-size: 50px;
    color:red;
    background-color: antiquewhite;
}

index.html:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Title</title>
    <link rel="stylesheet" href="/css/index.css">
</head>
<body>
{{.title | safe}}
</body>
</html>

页面:
GoWeb -- gin框架的入门和使用(2)

会话

会话控制涉及到cookie 和 session的使用

cookie

1、HTTP是无状态协议,服务器不能记录浏览器的访问状态,也就是说服务器不能区分两次请求是否由同一个客户端发出
2、Cookie就是解决HTTP协议无状态的方案之一
3、Cookie实际上就是服务器保存在浏览器上的一段信息,浏览器有了Cookie之后,每次向服务器发送请求时都会将该信息发送给服务器,服务器收到请求之后,就可以根据该信息处理请求
4、Cookie由服务器创建,并发送给浏览器,最终由浏览器保存

设置cookie

func (c *Context) SetCookie(name,value string,maxAge int,path,domain string,secure,httpOnly bool)

参数说明:
GoWeb -- gin框架的入门和使用(2)

	//cookie
	r.GET("/cookies", func(context *gin.Context) {
		context.SetCookie("site_cookie", "cookievalue", 3600, "/", "localhost", false, true)
		
	})

GoWeb -- gin框架的入门和使用(2)
这样就成功设置好了cookie

读取cookie

	//read cookie
	r.GET("/read", func(context *gin.Context) {
		//根据cookie名字读取cookie值
		data, err := context.Cookie("site_cookie")
		if err != nil {
			//返回cookie值
			context.String(200, "not found")
			return
		}

		context.String(200, data)
	})

GoWeb -- gin框架的入门和使用(2)

删除cookie

通过将cookie的MaxAge设置为-1,就能达到删除cookie的目的

	//delete cookie
	
	r.GET("/del", func(context *gin.Context) {
		context.SetCookie("site_cookie", "cookievalue", -1, "/", "localhost", false, true)

	})

GoWeb -- gin框架的入门和使用(2)
可以发现先前设置的cookie已经被删除了文章来源地址https://www.toymoban.com/news/detail-464989.html

到了这里,关于GoWeb -- gin框架的入门和使用(2)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • goweb入门

    创建gomod项目 新建main.go 创建launch.json 启动项目访问http://127.0.0.1:8080/

    2024年02月09日
    浏览(25)
  • GIN框架介绍以及使用

    Gin 是一个用Go语言编写的web框架。它是一个类似于martini但拥有更好性能的API框架, 由于使用了httprouter,速度提高了近40倍。 如果你是性能和高效的追求者, 你会爱上Gin,而且现在大多数企业都在使用Gin框架,反正学一学总没有错。 Go世界里最流行的Web框架,Github上有32K+star。

    2024年02月22日
    浏览(31)
  • Go -【gin】框架搭建基本使用

    Gin是一个快速的Golang web框架,它使用了httprouter来处理路由和速度,而不是使用内置的Go路由。以下是Gin框架的搭建和使用: 这将从Gin GitHub仓库中安装最新版本的Gin框架。 在搭建一个Gin应用程序之前,让我们了解一下Gin的基本架构: Router :它是Gin应用程序的核心部分,它接

    2024年02月16日
    浏览(28)
  • 使用Gin框架搭配WebSocket完成实时聊天

    在写项目的时候,需要完成实时聊天的功能,于是简单的学习下WebSocket,想知道WebSocket是什么的小伙伴可以去网上别的地方学习一下。 要实现实时聊天,网上的大部分内容都是SpringBoot和WebSocket完成的,但是我使用Go写的,所以让我们来学习一下Gin框架搭配WebSocket完成实时聊天

    2024年02月16日
    浏览(21)
  • gin框架使用系列之三——获取表单数据

    系列目录 《gin框架使用系列之一——快速启动和url分组》 《gin框架使用系列之二——uri占位符和占位符变量的获取》 get请求的参数是直接加在url后面的,在gin中获取get请求的参数主要用Query()和DefaultQuery()两个方法,示例代码如下 在浏览器中输入全部参数的运行如下: 如果

    2024年02月04日
    浏览(28)
  • [golang gin框架] 26.Gin 商城项目-前台自定义商品列表模板, 商品详情数据渲染,Markdown语法使用

    当在首页分类点击进入分类商品列表页面时,可以根据后台分类中的分类模板跳转到对应的模板商品列表页面 (1).商品控制器方法Category()完善 修改controllers/frontend/productController.go中的方法Category(), 判断分类模板,如果后台没有设置,则使用默认模板 (2).模板页面案例 先来回顾一

    2024年02月01日
    浏览(35)
  • 使用Go-Gin框架实现 OSS 前端直传功能

    在现代 Web 应用中,文件上传是一项常见功能。传统的上传方式通常需要文件经过后端服务器转发到对象存储服务(如阿里云 OSS)。然而,这种方法可能对服务器造成额外的负担,并降低上传效率。本文将探讨如何使用 Go-Gin 框架实现 OSS 前端直传,从而提高效率并减轻服务器

    2024年01月18日
    浏览(41)
  • Go 语言之在 gin 框架中使用 zap 日志库

    gin.Default() 的源码 Logger(), Recovery() 实操 运行并访问:http://localhost:8080/hello test.log 其它参考:https://github.com/gin-contrib/zap

    2024年02月09日
    浏览(25)
  • [golang gin框架] 37.ElasticSearch 全文搜索引擎的使用

    ElasticSearch 是一个基于 Lucene 的 搜索服务器 ,它提供了一个 分布式多用户 能力的 全文搜索引擎 ,基于 RESTful web 接口,Elasticsearch 是用 Java 开发的,并作为 Apache 许可条款下的开放源码发布,是当前流行的企业级搜索引擎,设计用于云计算中,能够达到 实时搜索 , 稳定 , 可靠

    2024年02月11日
    浏览(42)
  • Gin框架: 使用go-ini配置参数与不同环境下的配置部署

    关于 INI 配置文件与go-ini 1 )概述 在INI配置文件中可以处理各种数据的配置 INI文件是一种简单的文本格式,常用于配置软件的各种参数 go-ini 是地表 最强大、最方便 和 最流行 的 Go 语言 INI 文件操作库 Github 地址:https://github.com/go-ini/ini 官方文档: https://ini.unknwon.io/ 使用示例

    2024年02月22日
    浏览(30)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包