Go语言GIN框架安装与入门

news/2024/9/16 17:45:43/

Go语言GIN框架安装与入门

文章目录

  • Go语言GIN框架安装与入门
    • 1. 创建配置环境
    • 2. 配置环境
    • 3. 下载最新版本Gin
    • 4. 编写第一个接口
    • 5. 静态页面和资源文件加载
    • 6. 各种传参方式
      • 6.1 URL传参
      • 6.2 路由形式传参
      • 6.3 前端给后端传递JSON格式
      • 6.4 表单形式传参
    • 7. 路由和路由组
    • 8. 项目代码main.go
    • 9. 总结

之前学习了一周的GO语言,学会了GO语言基础,现在尝试使用GO语言最火的框架GIN来写一些简单的接口。看了B站狂神说的GIN入门视频,基本明白如何写接口了,下面记录一下基本的步骤。

1. 创建配置环境

我们使用Goland创建第一个新的开发环境,这里只要在windows下面安装好Go语言,Goroot都能自动识别。
在这里插入图片描述
新的项目也就只有1个go.mod的文件,用来表明项目中使用到的第三方库。
在这里插入图片描述

2. 配置环境

我们使用第三方库是需要从github下载的,但是github会经常连不上,所以我们就需要先配置第三方的代理地址。我们再Settings->Go->Go Modules->Environment下面配上代理地址。

GOPROXY=https://goproxy.cn,direct

在这里插入图片描述

3. 下载最新版本Gin

在IDE里面的Terminal下面安装Gin框架,使用下面的命令安装Gin,安装完成以后,go.mod下面require就会自动添加依赖。

go get -u github.com/gin-gonic/gin

在这里插入图片描述

4. 编写第一个接口

创建main.go文件,然后编写以下代码,这里定义了一个/hello的路由。

package mainimport "github.com/gin-gonic/gin"func main() {ginServer := gin.Default()ginServer.GET("/hello", func(context *gin.Context) {context.JSON(200, gin.H{"msg": "hello world"})})ginServer.Run(":8888")}

编译运行通过浏览器访问,就可以输出JSON。

在这里插入图片描述

5. 静态页面和资源文件加载

使用下面代码加入项目下面的静态页面(HTML文件),以及动态资源(JS)。

	// 加载静态页面ginSever.LoadHTMLGlob("templates/*")// 加载资源文件ginSever.Static("/static", "./static")

这是项目的资源文件列表
在这里插入图片描述
其中index.html文件如下

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>我的第一个GO web页面</title><link rel="stylesheet" href="/static/css/style.css"><script src="/static/js/common.js"></script>
</head>
<body><h1>谢谢大家支持</h1>获取后端的数据为:
{{.msg}}<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></body>
</html>

接着就可以响应一个页面给前端了。

	// 响应一个页面给前端ginSever.GET("/index", func(context *gin.Context) {context.HTML(http.StatusOK, "index.html", gin.H{"msg": "这是go后台传递来的数据",})})

在这里插入图片描述

6. 各种传参方式

6.1 URL传参

在后端获取URL传递来的参数。

	// 传参方式//http://localhost:8082/user/info?userid=123&username=dfaginSever.GET("/user/info", myHandler(), func(context *gin.Context) {// 取出中间件中的值usersession := context.MustGet("usersession").(string)log.Println("==========>", usersession)userid := context.Query("userid")username := context.Query("username")context.JSON(http.StatusOK, gin.H{"userid":   userid,"username": username,})})

其中上面多加了一个中间键,就是接口代码运行之前执行的代码,myHandler的定义如下:

// go自定义中间件
func myHandler() gin.HandlerFunc {return func(context *gin.Context) {// 设置值,后续可以拿到context.Set("usersession", "userid-1")context.Next() // 放行}
}

6.2 路由形式传参

	// http://localhost:8082/user/info/123/dfaginSever.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,})})

6.3 前端给后端传递JSON格式

	// 前端给后端传递jsonginSever.POST("/json", func(context *gin.Context) {// request.bodydata, _ := context.GetRawData()var m map[string]interface{}_ = json.Unmarshal(data, &m)context.JSON(http.StatusOK, m)})

6.4 表单形式传参

	ginSever.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,})})

7. 路由和路由组

	// 路由ginSever.GET("/test", func(context *gin.Context) {context.Redirect(http.StatusMovedPermanently, "https://www.baidu.com")})// 404ginSever.NoRoute(func(context *gin.Context) {context.HTML(http.StatusNotFound, "404.html", nil)})// 路由组userGroup := ginSever.Group("/user"){userGroup.GET("/add")userGroup.POST("/login")userGroup.POST("/logout")}orderGroup := ginSever.Group("/order"){orderGroup.GET("/add")orderGroup.DELETE("delete")}

8. 项目代码main.go

package mainimport ("encoding/json""github.com/gin-gonic/gin""log""net/http"
)// go自定义中间件
func myHandler() gin.HandlerFunc {return func(context *gin.Context) {// 设置值,后续可以拿到context.Set("usersession", "userid-1")context.Next() // 放行}
}func main() {// 创建一个服务ginSever := gin.Default()//ginSever.Use(favicon.New("./icon.png"))// 加载静态页面ginSever.LoadHTMLGlob("templates/*")// 加载资源文件ginSever.Static("/static", "./static")//ginSever.GET("/hello", func(context *gin.Context) {//	context.JSON(200, gin.H{"msg": "hello world"})//})//ginSever.POST("/user", func(c *gin.Context) {//	c.JSON(200, gin.H{"msg": "post,user"})//})//ginSever.PUT("/user")//ginSever.DELETE("/user")// 响应一个页面给前端ginSever.GET("/index", func(context *gin.Context) {context.HTML(http.StatusOK, "index.html", gin.H{"msg": "这是go后台传递来的数据",})})// 传参方式//http://localhost:8082/user/info?userid=123&username=dfaginSever.GET("/user/info", myHandler(), func(context *gin.Context) {// 取出中间件中的值usersession := context.MustGet("usersession").(string)log.Println("==========>", usersession)userid := context.Query("userid")username := context.Query("username")context.JSON(http.StatusOK, gin.H{"userid":   userid,"username": username,})})// http://localhost:8082/user/info/123/dfaginSever.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,})})// 前端给后端传递jsonginSever.POST("/json", func(context *gin.Context) {// request.bodydata, _ := context.GetRawData()var m map[string]interface{}_ = json.Unmarshal(data, &m)context.JSON(http.StatusOK, m)})// 表单ginSever.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,})})// 路由ginSever.GET("/test", func(context *gin.Context) {context.Redirect(http.StatusMovedPermanently, "https://www.baidu.com")})// 404ginSever.NoRoute(func(context *gin.Context) {context.HTML(http.StatusNotFound, "404.html", nil)})// 路由组userGroup := ginSever.Group("/user"){userGroup.GET("/add")userGroup.POST("/login")userGroup.POST("/logout")}orderGroup := ginSever.Group("/order"){orderGroup.GET("/add")orderGroup.DELETE("delete")}// 端口ginSever.Run(":8888")}

9. 总结

以上就是Gin入门的所有内容了,大家觉得还有帮助,欢迎点赞收藏哦。


http://www.ppmy.cn/news/1040033.html

相关文章

【Git】SSH到底是什么

一、SSH初探 1、SSH是什么&#xff1f; SSH是一个安全协议&#xff0c;类似有SSL、TSL Git有四种协议&#xff1a;本地协议、Git协议、HTTP协议、SSH协议 SSH协议的优缺点&#xff1a; 优点&#xff1a;SSH访问更加安全&#xff0c;有利于公司的开发维护&#xff0c;并且可…

linux系统中的中文显示问题

经常遇到这种情况&#xff1a;某些项目的文件中不可避免地包含有中文&#xff0c;在Windows系统中没有任何问题&#xff0c;拷到Linux系统中就出问题了。 1. Linux系统设置 $echo $LANG en_US.iso885915 朋友建议我设置为&#xff1a; export LANGzh_CN.utf8 但我这样设置之…

webrtc学习(六)重要信令级时序图

一.四个重要信令 1.用户登录信令 SignIn 2..用户登出信令 SignOut 3..用户等待信令 wait信令是指从服务器的消息队列中获取暂存的中转消息&#xff0c;比如说sdp消息&#xff0c;对于信令服务器来说&#xff0c;他没有办法给用户推送消息&#xff0c;只能是用户推送消息给…

小知识积累

1、使用JSON.parse(JSON.stringify()) 深拷贝时会出现的问题 var obj {a: "zs",b: undefined,c: Symbol("score"),d: null,e: function () {console.log("show");},};console.log(JSON.parse(JSON.stringify(obj)));很明显undefined、函数、sym…

常量(constant)

1、概述 常量&#xff1a;是指在Java程序运行期间固定不变的数据。 2、分类 类型含义数据举例整数常量所有的整数0&#xff0c;1&#xff0c;567&#xff0c;-9 小数常量 &#xff08;浮点数常量&#xff09; 所有的小数0.0&#xff0c;-0.1&#xff0c;2.55字符常量单引号引起…

2022年12月 C/C++(二级)真题解析#中国电子学会#全国青少年软件编程等级考试

第1题:数组逆序重放 将一个数组中的值按逆序重新存放。例如,原来的顺序为8,6,5,4,1。要求改为1,4,5,6,8。 输入 输入为两行:第一行数组中元素的个数n(1 输出 输出为一行:输出逆序后数组的整数,每两个整数之间用空格分隔。 样例输入 5 8 6 5 4 1 样例输出 1 4 5 6 8 以下是…

手写spring笔记

手写spring笔记 《Spring 手撸专栏》笔记 IoC部分 Bean初始化和属性注入 Bean的信息封装在BeanDefinition中 /*** 用于记录Bean的相关信息*/ public class BeanDefinition {/*** Bean对象的类型*/private Class beanClass;/*** Bean对象中的属性信息*/private PropertyVal…

【爬虫】Requests库的使用

这个库比我们上次说的 urllib 可是要牛逼一丢丢的。通过它我们可以用更少的代码&#xff0c;模拟浏览器操作。 不多说&#xff0c;直接上手代码。 requests 常见用法 mport requests# get请求网站 r requests.get(https://www.baidu.com/) # 获取服务器响应文本内容 r.text …

虚拟拍摄,如何用stable diffusion制作自己的形象照?

最近收到了某活动的嘉宾邀请&#xff0c;我将分享&#xff1a; 主题&#xff1a;生成式人工智能的创新实践 简要描述&#xff1a;从品牌营销、智能体、数字内容创作、下一代社区范式等方面&#xff0c;分享LLM与图像等生成式模型的落地应用与实践经验。 领域/研究方向&#xff…

Linux常用命令详细大全

目录 1、查看目录与文件&#xff1a;ls2、切换目录&#xff1a;cd3、显示当前目录&#xff1a;pwd4、创建空文件&#xff1a;touch5、创建目录&#xff1a;mkdir6、查看文件内容&#xff1a;cat7、分页查看文件内容&#xff1a;more8、查看文件尾内容&#xff1a;tail9、拷贝&a…

2023河南萌新联赛第(六)场:河南理工大学-F 爱睡大觉的小C

2023河南萌新联赛第&#xff08;六&#xff09;场&#xff1a;河南理工大学-F 爱睡大觉的小C https://ac.nowcoder.com/acm/contest/63602/F 文章目录 2023河南萌新联赛第&#xff08;六&#xff09;场&#xff1a;河南理工大学-F 爱睡大觉的小C题意解题思路 题意 新学期的概…

2.SpringMvc中Model、ModelMap和ModelAndView使用详解

1.前言 最近SSM框架开发web项目&#xff0c;用得比较火热。spring-MVC肯定用过&#xff0c;在请求处理方法可出现和返回的参数类型中&#xff0c;最重要就是Model和ModelAndView了&#xff0c;对于MVC框架&#xff0c;控制器Controller执行业务逻辑&#xff0c;用于产生模型数据…

❤ 全面解析若依框架vue2版本(springboot-vue前后分离--前端部分)

❤ 解析若依框架之前台修改 1、修改页面标题和logo 修改网页上的logo ruoyi-ui --> public --> favicon.ico&#xff0c;把这个图片换成你自己的logo 修改网页标题 根目录下的vue.config.js const name process.env.VUE_APP_TITLE || ‘若依管理系统’ // 网页标题 换成…

Redis与MySQL的比较:什么情况下使用Redis更合适?什么情况下使用MySQL更合适?

Redis和MySQL是两种不同类型的数据库&#xff0c;各有自己的特点和适用场景。下面是Redis和MySQL的比较以及它们适合使用的情况&#xff1a; Redis适合的场景&#xff1a; 高性能读写&#xff1a;Redis是基于内存的快速Key-Value存储&#xff0c;读写性能非常高。它适用于需要…

神经网络基础-神经网络补充概念-56-迁移学习

迁移学习&#xff08;Transfer Learning&#xff09;是一种机器学习技术&#xff0c;旨在将在一个任务上学到的知识或模型迁移到另一个相关任务上&#xff0c;以提高新任务的性能。迁移学习的核心思想是通过利用源领域&#xff08;source domain&#xff09;的知识来改善目标领…

【SA8295P 源码分析】76 - Thermal 功耗 之 /dev/thermalmgr 相关调试命令汇总

【SA8295P 源码分析】76 - Thermal 功耗 之 /dev/thermalmgr 相关调试命令汇总 1、配置文件:/mnt/etc/system/config/thermal-engine.conf2、获取当前SOC所有温度传感器的温度:cat /dev/thermalmgr3、查看所有 Thermal 默认配置和自定义配置:echo query config > /dev/th…

自动驾驶,一次道阻且长的远征|数据猿直播干货分享

‍数据智能产业创新服务媒体 ——聚焦数智 改变商业 在6月的世界人工智能大会上&#xff0c;马斯克在致辞中宣称&#xff0c;到2023年底&#xff0c;特斯拉便可实现L4级或L5级的完全自动驾驶&#xff08;FSD&#xff09;。两个月之后&#xff0c;马斯克又在X社交平台上发言&am…

线程同步条件变量

为何要线程同步 在线程互斥中外面解决了多线程访问共享资源所会造成的问题。 这篇文章主要是解决当多线程互斥后引发的新的问题&#xff1a;线程饥饿的问题。 什么是线程饥饿&#xff1f;互斥导致了多线程对临界区访问只能改变为串行&#xff0c;这样访问临界资源的代码只能…

gromacs教程练习1

gromacs能在win上运行&#xff0c;还是个开源的软件&#xff0c;这都很值得入手学习 记录下gromacs教程的练习情况&#xff1a; Lysozyme in water 水中的溶菌酶&#xff0c;嗯&#xff0c;估计就是把蛋白处理后放在显试溶剂里跑MD这个模拟。 1、文件的准备&#xff1a; 1、…

系统架构设计师---计算机基础知识之数据库系统结构与规范化

目录 一、基本概念 二、 数据库的结构 三、常用的数据模型 概念数据模型