欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 维修 > gin框架学习

gin框架学习

2025/5/6 18:37:25 来源:https://blog.csdn.net/2301_80148821/article/details/144409242  浏览:    关键词:gin框架学习

gin框架是什么

gin框架是一个用Go语言编写的web框架,其主要可以用于微服务开发等项目使用

goland快速安装gin

直接使用goland进行创建一个新项目即可

![[Pasted image 20241116194154.png]]

然后编写如下代码并运行(爆红忽略即可),

package main  import (  "github.com/gin-gonic/gin"  
)  func main() {  // 创建一个默认的路由引擎  r := gin.Default()  // GET:请求方式;/hello:请求的路径  // 当客户端以GET方法请求/hello路径时,会执行后面的匿名函数  r.GET("/hello", func(c *gin.Context) {  // c.JSON:返回JSON格式的数据 gin.H 是map[string]interface{}的缩写   
c.JSON(200, gin.H{  "message": "Hello",  })  })  // 启动HTTP服务,默认在0.0.0.0:8080启动服务  r.Run()  
}

运行后可以发现报错

![[Pasted image 20241116194559.png]]

点击下面的go get即可进行下载

下载完成会显示编译成功即可运行代码

gin简单学习

创建服务

使用gin.Default()方法进行创建一个服务。

其不仅创建了一个Gin引擎,还自动注册了一些默认的中间件。

并且这个函数返回的是一个 *gin.Engine类型对象,这个对象是Gin的核心,用来处理HTTP请求和路由。

而除了gin.Default方法之外,还有一个gin.New()方法也可以进行创建服务,这个函数创建出的引擎是没有添加任何默认中间件的引擎实例,所有操作都可以自己进行,更加灵活。

package main  import "github.com/gin-gonic/gin"  func main() {  //创建一个服务  ginServer := gin.Default()  
}

创建请求内容

使用ginServer.GET,或者ginServer.POST进行创建GET请求或者POST请求的路由。

这俩个方法都接收俩个参数,第一个为路由路径,第二个为路由处理函数,当访问这个路由时就会触发后面的路由处理函数。

import (  "github.com/gin-gonic/gin"  
)  func main() {  //创建一个服务  ginServer := gin.Default()  //创建一个get请求  ginServer.GET("/hello", func(context *gin.Context) {  context.JSON(200, gin.H{"msg": "hello"})  })

运行服务

使用的是.Run方法,Run方法启动一个HTTP服务器,开始监听并传入的请求,其接收参数为指定监听的端口

package main  import (  "github.com/gin-gonic/gin"  
)  func main() {  //创建一个服务  ginServer := gin.Default()  //创建一个get请求  ginServer.GET("/hello", func(context *gin.Context) {  context.JSON(200, gin.H{"msg": "hello"})  })  //服务器端口,以及运行服务  ginServer.Run(":8081")  
}

运行后访问127.0.0.1:8081/hello即可看到hello数据被输出

RESTful API实现

使用不同的请求访问页面时,可以通过定义不同的请求方法来实现不同的功能。

并且,在gin框架中,还有一个可以匹配所有请求方法的Any方法。

package main  import (  "github.com/gin-gonic/gin"  
)  func main() {  //创建一个服务  ginServer := gin.Default()  //创建一个get请求  ginServer.GET("/hello", func(context *gin.Context) {  context.JSON(200, gin.H{"msg": "hello"})  })  ginServer.POST("/user", func(context *gin.Context) {  context.JSON(200,gin.H{"msg":"POST"})  })  ginServer.PUT("/user", func(context *gin.Context) {  context.JSON(200,gin.H{"msg":"PUT"})  })  //服务器端口,以及运行服务  ginServer.Run(":8082")  
}

可以使用burpsuit进行测试实现。

响应加载前端页面

使用静态文件

静态文件一般使用Static()方法进行设置,Static方法将某一个目录下的静态资源(HTML,CSS,JS等)映射到指定目录中。

index.html

<!DOCTYPE html>  
<html lang="en">  
<head>  <meta charset="UTF-8">  <title>Hello Go WEB</title>  
</head>  
<body>  
<h1>WEB</h1>  
</body>  
</html>
package mainimport ("github.com/gin-gonic/gin"
)func main() {// 创建Gin路由r := gin.Default()// 设置静态文件路径r.Static("/assets", "./public")// 启动服务器r.Run(":8080")
}

这样即可加载index.html到/index中

gin模版引擎渲染动态页面

其主要使用了LoadHTMLGlob方法来指定加载哪个目录下的HTML文件。

并且使用c.HTML来渲染并返回指定的界面。

index.html

<!DOCTYPE html>  
<html lang="en">  
<head>  <meta charset="UTF-8">  <title>Hello Go WEB</title>  
</head>  
<body>  
<h1>WEB</h1>  
{{.msg}}  
</body>  
</html>

go

package main  import (  "github.com/gin-gonic/gin"  
)  func main() {  // 创建Gin路由  r := gin.Default()  r.LoadHTMLGlob("public/*")  r.GET("/index", func(context *gin.Context) {  context.HTML(200, "index.html", gin.H{  "msg": "Go Web",  })  })  // 启动服务器  r.Run(":8080")  
}

gin框架加载资源文件

使用Static方法进行加载资源文件

index.js

alert("Hacker")

static.css

body{  background: red;  
}

main.go

package main  import (  "github.com/gin-gonic/gin"  
)  func main() {  // 创建Gin路由  r := gin.Default()  r.LoadHTMLGlob("public/*")  r.Static("/static", "./static")  r.GET("/index", func(context *gin.Context) {  context.HTML(200, "index.html", gin.H{  "msg": "Go Web",  })  })  // 启动服务器  r.Run(":8080")  
}

获取请求参数

获取url请求参数

使用c.Param()获取指定参数

package main  import (  "github.com/gin-gonic/gin"  "net/http")  func main() {  // 创建Gin路由  r := gin.Default()  r.LoadHTMLGlob("public/*")  r.Static("/static", "./static")  r.GET("/index", func(context *gin.Context) {  context.HTML(200, "index.html", gin.H{  "msg": "Go Web",  })  })  r.GET("/get/:id", func(context *gin.Context) {  id := context.Param("id")  context.JSON(http.StatusOK, gin.H{  "id": id,  })  })  // 启动服务器  r.Run(":8080")  
}

获取get请求参数

使用DefaultQuery()或Query()方法获取,这俩个方法的区别是,DefaultQuery()方法可以设置无参数传入时的默认值,而Query方法直接返回空字符串

package main  import (  "github.com/gin-gonic/gin"  "net/http")  func main() {  // 创建Gin路由  r := gin.Default()  r.LoadHTMLGlob("public/*")  r.Static("/static", "./static")  r.GET("/index", func(context *gin.Context) {  context.HTML(200, "index.html", gin.H{  "msg": "Go Web",  })  })  r.GET("/get", func(context *gin.Context) {  id := context.Query("id")  pass := context.DefaultQuery("pass", "123456")  context.JSON(http.StatusOK, gin.H{  "id":   id,  "pass": pass,  })  })  // 启动服务器  r.Run(":8080")  
}

获取post请求参数

主要使用DefaultPostForm和PostForm方法来获取参数,区别和上面一样

package main  import (  "github.com/gin-gonic/gin"  "net/http")  func main() {  // 创建Gin路由  r := gin.Default()  r.LoadHTMLGlob("public/*")  r.Static("/static", "./static")  r.GET("/index", func(context *gin.Context) {  context.HTML(200, "index.html", gin.H{  "msg": "Go Web",  })  })  r.POST("/get", func(context *gin.Context) {  id := context.PostForm("id")  pass := context.DefaultPostForm("pass", "123456")  context.JSON(http.StatusOK, gin.H{  "id":   id,  "pass": pass,  })  })  // 启动服务器  r.Run(":8080")  
}

获取json请求体参数

使用BindJson方法来获取数据

package main  import (  "github.com/gin-gonic/gin"  "net/http")  type User struct {  Name string `json:"name"`  Age  int    `json:"age"`  
}  func main() {  // 创建Gin路由  r := gin.Default()  r.LoadHTMLGlob("public/*")  r.Static("/static", "./static")  r.GET("/index", func(context *gin.Context) {  context.HTML(200, "index.html", gin.H{  "msg": "Go Web",  })  })  r.POST("/get", func(context *gin.Context) {  var user User  context.BindJSON(&user)  context.JSON(http.StatusOK, gin.H{  "name": user.Name,  "age":  user.Age,  })  })  // 启动服务器  r.Run(":8080")  
}

获取请求头

可以使用GetHeader函数来获取请求头的特定字段

package main  import (  "github.com/gin-gonic/gin"  "net/http")  func main() {  // 创建Gin路由  r := gin.Default()  r.LoadHTMLGlob("public/*")  r.Static("/static", "./static")  r.GET("/index", func(context *gin.Context) {  context.HTML(200, "index.html", gin.H{  "msg": "Go Web",  })  })  r.GET("/get", func(context *gin.Context) {  header := context.GetHeader("Connection")  context.JSON(http.StatusOK, gin.H{  "header": header,  })  })  // 启动服务器  r.Run(":8080")  
}

获取表单参数

package main  import (  "github.com/gin-gonic/gin"  "net/http")  func main() {  // 创建Gin路由  r := gin.Default()  r.LoadHTMLGlob("public/*")  r.Static("/static", "./static")  r.GET("/index", func(context *gin.Context) {  context.HTML(200, "index.html", gin.H{  "msg": "Go Web",  })  })  r.POST("user/login", func(context *gin.Context) {  username := context.PostForm("username")  password := context.PostForm("password")  context.JSON(http.StatusOK, gin.H{  "username": username,  "passwoed": password,  })  })  // 启动服务器  r.Run(":8080")  
}

index.html

<!DOCTYPE html>  
<html lang="en">  
<head>  <meta charset="UTF-8">  <title>Hello Go WEB</title>  <link rel="stylesheet" href="../static/static.css">  <script src="../static/index.js"></script>  
</head>  
<body>  
<form action="/user/login" 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>

路由

重定向

路由重定向使用的方法为 Redirect方法,Redirect方法接收俩个参数;一个是状态码,通常使用 http.StatusFound(302)或者 http.StatusMovedPermanently(301)来表示重定向,另一个是重定向到的url,表示重定向到哪里去

package main  import (  "github.com/gin-gonic/gin"  "net/http")  func main() {  // 创建Gin路由  r := gin.Default()  r.LoadHTMLGlob("public/*")  r.Static("/static", "./static")  r.GET("/index", func(context *gin.Context) {  context.HTML(200, "index.html", gin.H{  "msg": "Go Web",  })  })  r.GET("/search", func(context *gin.Context) {  context.Redirect(http.StatusMovedPermanently, "https://www.baidu.com")  })  // 启动服务器  r.Run(":8080")  
}

路由组

gin中使用Group方法进行创建路由组

package main  import (  "github.com/gin-gonic/gin"  
)  func main() {  // 创建Gin路由  r := gin.Default()  r.LoadHTMLGlob("public/*")  r.Static("/static", "./static")  r.GET("/index", func(context *gin.Context) {  context.HTML(200, "index.html", gin.H{  "msg": "Go Web",  })  })  a :=r.Group("cat")  {  a.GET("/1", func(context *gin.Context) {  })  a.POST("2", func(context *gin.Context) {  })  }  // 启动服务器  r.Run(":8080")  
}

中间件

使用了Use方法来使用中间件。


package main  import (  "fmt"  "github.com/gin-gonic/gin"    "net/http")  func Logger() gin.HandlerFunc {  return func(c *gin.Context) {  fmt.Println("Logger middleware executed")  c.Next()  // 执行后续的处理函数  }  
}  func main() {  r := gin.Default()  // 使用中间件  r.Use(Logger())  r.GET("/test", func(c *gin.Context) {  c.String(http.StatusOK, "Test route")  })  r.Run(":8080")  }

使用gin编写一个简单的钓鱼网站

index.html

<!DOCTYPE html>  
<html lang="en">  
<head>  <meta charset="UTF-8">  <title>Hello Go WEB</title>  <link rel="stylesheet" href="../static/static.css">  <script src="../static/index.js"></script>  
</head>  
<body>  
<form action="/login" method="post">  <p>username:<input type="text" name="username"></p>  <p>password:<input type="text" name="password"></p>  <button type="submit">提交</button>  
</form>  {{.msg}}  
</body>  
</html>

main.go

package main  import (  "fmt"  "github.com/gin-gonic/gin"    "net/http"    "os")  const goo = 0  func main() {  file, err := os.OpenFile("example.txt", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)  if err != nil {  fmt.Println("Error opening file:", err)  return  }  defer file.Close()  r := gin.Default()  r.LoadHTMLGlob("public/*")  r.GET("/index", func(context *gin.Context) {  context.HTML(http.StatusOK, "index.html", gin.H{})  })  r.POST("/login", func(context *gin.Context) {  username := context.PostForm("username")  password := context.PostForm("password")  log := username + ":" + password + "\n"  file.WriteString(log)  context.Redirect(http.StatusMovedPermanently, "http://127.0.0.1:8080/index")  })  r.Run(":8080")  
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词