Golang | Gin(简洁版)

文章目录

安装使用

  • Gin 是一个 golang 的微框架,封装比较优雅,API 友好,源代码比较明确。具有快速灵活,容错方便等特点。其实对于 golang 而言,web 框架的依赖远比 python,java 之类的要小。自身的 net/http 足够简单,性能也非常不错。框架更像是一个常用函数或者工具的集合。借助框架开发,不仅可以省去很多常用的封装带来的时间,也有助于团队的编码风格和形成规范。
  • Gin 官方文档地址:https://gin-gonic.com/zh-cn.docs
  • 安装 Gin:
bash 复制代码
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
go 复制代码
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等)对资源进行操作。
go 复制代码
// 以前写网站
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:部分更新资源。
go 复制代码
	// 访问地址,处理请求 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"})
	})

响应页面

go 复制代码
	// 加载静态页面(全局加载)
	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传参方式
go 复制代码
	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风格请求参数
go 复制代码
	// :就可以直接取出这个值了
	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,
		})
	})
go 复制代码
	// 前端给后端传递 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,
		})
	})

路由讲解

go 复制代码
	ginServer.GET("/json", func(context *gin.Context) {
		// 重定向
		context.Redirect(http.StatusMovedPermanently, "https://www.4399.com")
	})
go 复制代码
	// 404 NoRoute
	ginServer.NoRoute(func(context *gin.Context) {
		context.Redirect(http.StatusNotFound, "404.html", nil)
	})
go 复制代码
	// 路由组
	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中间件可以进行预处理,登录授权、验证、分页等

	// 自定义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,
		})
	})
相关推荐
多加点辣也没关系15 分钟前
JavaScript|第41章:性能优化实战
开发语言·javascript·性能优化
Resean02231 小时前
架构设计系列(十六):DDD 与代码架构
java·开发语言·架构
码途行者2 小时前
每天10分钟学Go:第22课 自定义错误
开发语言·后端·golang
23图2 小时前
C 语言开散列表(拉链法)拆解:链挂得没错,key=-1 会去读 T[-1]
c语言·开发语言·散列表
feixing_fx3 小时前
解构与展开:可读性和性能的取舍
开发语言·前端·javascript·前端框架
小飞在努力3 小时前
【实现负载均匀在线判题③】从零散模块到统一,编译运行全链路封装
c语言·开发语言·c++·笔记
饮水桶_T6 小时前
C++ stack & queue复习笔记
开发语言·笔记·算法
炸膛坦客7 小时前
单片机/C/C++八股:(三十四)C 语言函数参数入栈顺序
c语言·开发语言·c++
咖啡八杯8 小时前
LoginUser 适配器模式:适配 SysUser 到 UserDetails
java·开发语言·后端·框架·适配器模式·若依
码途行者8 小时前
每天10分钟学Go:第20课 泛型
c++·算法·golang