当前位置: 首页 > news >正文

Golang | Gin(简洁版)

文章目录

    • 安装使用
    • RESTful API
    • 响应页面
    • 获取请求参数
    • 路由讲解
    • 中间件

安装使用

  • Gin 是一个 golang 的微框架,封装比较优雅,API 友好,源代码比较明确。具有快速灵活,容错方便等特点。其实对于 golang 而言,web 框架的依赖远比 python,java 之类的要小。自身的 net/http 足够简单,性能也非常不错。框架更像是一个常用函数或者工具的集合。借助框架开发,不仅可以省去很多常用的封装带来的时间,也有助于团队的编码风格和形成规范。
  • Gin 官方文档地址:https://gin-gonic.com/zh-cn.docs
  • 安装 Gin:
go get -u github.com/gin-gonic/gin
  • 在 windows 10 系统中,安装 Go1.19 之后的版本,然后打开 go module,在命令行终端中输入:go env -w GO111MODULE=on
  • 修改指定的代理,在命令行终端中输入:go env -w GOPROXY=https:/lgoproxy.io,direct
package main

import "github.com/gin-gonic/gin"
import "github.com/thinkerou/favicon"

func main() {
	// 创建一个服务
	ginServer := gin.Default()

	// 为网页标签导入一个icon
	ginServer.Use(favicon.New("path/to/your/icon"))

	// 连接数据库的代码
	
	// 访问地址,处理请求 Request Response
	ginServer.GET("/hello", func(context *gin.Context) {
		context.JSON(200, gin.H{"msg": "Hello World!"})
	})
	// gin.H 其实就是一个 map[string]any
	
	// 服务器端口
	ginServer.Run(":8082")
}

RESTful API

  • RESTful API(Representational State Transfer API)是一种基于REST架构风格的网络应用编程接口,它通过HTTP协议进行通信,常用于Web服务的实现。RESTful API遵循一些基本的设计原则,使得服务更加灵活、简单和易于维护。
  • REST的核心思想是通过定义资源(Resource)并通过HTTP动词(GET、POST、PUT、DELETE等)对资源进行操作。
// 以前写网站
get /user
post /create_user
post /update_user
post /delete_user

// RESTful API
get /user
post /user
put /user
delete /user
  • GET:获取资源,不修改服务器上的数据。
  • POST:创建新的资源,通常用于提交数据。
  • PUT:更新资源,用于替代现有资源。
  • DELETE:删除资源。
  • PATCH:部分更新资源。
	// 访问地址,处理请求 Request Response
	// Gin RestFul 十分简单
	ginServer.GET("/hello", func(context *gin.Context) {
		context.JSON(200, gin.H{"msg": "Hello World!"})
	})
	ginServer.POST("/user", func(context *gin.Context) {
		context.JSON(200, gin.H{"msg": "Post user"})
	})
	ginServer.PUT("/user", func(context *gin.Context) {
		context.JSON(200, gin.H{"msg": "Put user"})
	})
	ginServer.DELETE("/user", func(context *gin.Context) {
		context.JSON(200, gin.H{"msg": "Delete user"})
	})

响应页面

	// 加载静态页面(全局加载)
	ginServer.loadHTMLGlob("templates/*")
	
	// 加载资源文件
	gin.Server.Static("./static","./static")

	// 响应一个页面给前端
	ginServer.GET("/index", func(context *gin.Context) {
		// context.JSON()  json数据
		context.HTML(http.StatusOK, "index.html", gin.H{
			"msg":"This is the data form server."
		})
		//  前端用 {{.msg}} 赋值表达式即可取出
	})

获取请求参数

  • url?userid=1&username=z3,url传参方式
	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,
		})
	})
  • url/user/info/1/z3,RestFul风格请求参数
	// :就可以直接取出这个值了
	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
	ginServer.GET("/json", func(context *gin.Context) {
		// request.body
		b, _ := context.GetRawData()
		var m map[string]interface{}
		// 返回的是byte切片,包装为json数据
		_ = json.Unmarshal(b, &m)
		context.JSON(http.StatusOK, m)
	})
	
	// 处理表单
	ginServer.GET("/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("/json", func(context *gin.Context) {
		// 重定向
		context.Redirect(http.StatusMovedPermanently, "https://www.4399.com")
	})
	// 404 NoRoute
	ginServer.NoRoute(func(context *gin.Context) {
		context.Redirect(http.StatusNotFound, "404.html", nil)
	})
	// 路由组
	userGroup := ginServer.Group("/user"){
		userGroup.POST("/add", func)
		userGroup.POST("/login", func)
		userGroup.POST("/logout", func)
	}
	orderGroup := ginServer.Group("/order"){
		orderGroup.POST("/add", func)
		orderGroup.DELETE("/delete", func)
	}

中间件

	// go中间件可以进行预处理,登录授权、验证、分页等

	// 自定义go中间件 拦截器
	func myHandler() (gin.HandlerFunc) {
		return func(context *gin.Context) {
			// 通过自定义的中间件,设置的值在后续处理只要调用了这个中间件都可以拿到这里的值
			context.Set("usersession", "userid-1")
			if condition {
				context.Next() // 放行
			} else {
				context.Abort() // 阻止
			}
		}
	}


	ginServer.GET("/user/info", myHandler(), func(context *gin.Context) {
		// 取出中间件中的值
		usersession := context.MustGet("userSession").(string)
		log.Println("userSession", usersession)

		userid := context.Query("userid")
		username := context.Query("username")
		context.JSON(http.StatusOK, gin.H {
			"userid":userid,
			"username":username,
		})
	})

相关文章:

  • 深入Flink运行时架构:JobManager与TaskManager协作全解析
  • numpy常用函数详解
  • vulnhub靶场之【digitalworld.local系列】的FALL靶机
  • Java中,BIO、NIO和AIO三种模型的区别和适用场景
  • scala类型检测和转换
  • 1、stc89C52单片机简单使用
  • Linux基础操作
  • 每周一个网络安全相关工具——MetaSpLoit
  • 使用阿里云操作系统控制台排查内存溢出
  • 聊一聊 Android 的消息机制
  • 【蓝桥杯集训·每日一题2025】 AcWing 5540. 最大限度地提高生产力 python
  • kafka单机部署实战
  • laravel es 相关代码 ElasticSearch
  • UE4 World, Level, LevelStreaming从入门到深入
  • 【C++】vector(下):vector类的模拟实现(含迭代器失效问题)
  • OpenCV连续数字识别—可运行验证
  • Codeforces Round 973 (Div. 2) F. The Sum of the k-th Powers 数论、暴力
  • 前端杂的学习笔记
  • Java之IO流
  • winform基于antdui中table控件的使用
  • 微信网站收钱吗/网络营销专业的就业方向
  • 做ps彩图什么网站好/关键词seo服务
  • 简单的j网站建设方案书/网站seo是什么意思
  • 电商网站开发主要的三个软件/如何提升百度关键词排名
  • 零基础学软件测试难吗/seo提高关键词
  • 建立网站地图/重庆网站页面优化