文章目录
简介
- Go是一门正在快速增长的编程语言,专为构建简单、快速且可靠的软件而设计。golang提供的net/http库已经很好了,对于http的协议的实现非常好,基于此再造框架,也不会是难事,因此生态中出现了很多框架。
- Gin:Go语言编写的Web框架,以更好的性能实现类似Martini框架的APl。
- Gin是一个golang的微框架,封装比较优雅,API友好,源码注释比较明确。具有快速灵活,容错方便等特点。
- Beego:开源的高性能Go语言Web框架。
- beego是一个快速开发Go应用的http框架,go语言方面技术大牛。beego可以用来快速开发APl、Web、后端服务等各种应用,是一个RESTFu的框架,主要设计灵感来源于tornado、sinatra、flask这三个框架,但是结合了Go本身的一些特性(interface、struct继承等)而设计的一个框架。
- Iris:全宇宙最快的Go语言Web框架。完备MVC支持,未来尽在掌握。
- Iris是一个快速,简单但功能齐全的和非常有效的web框架。提供了一个优美的表现力和容易使用你的下一个网站或API的基础。
Gin安装
Gin是一个golang的微框架,封装比较优雅,API友好,源代码比较明确。具有快速灵活,容错方便等特点。其实对于golang而言,web框架的依赖远比Python,Java之类的要小。自身的net/http足够简单,性能也非常不错。框架更像是一个常用函数或者工具的集合。借助框架开发,不仅可以省去很多常用的封装带来的时间,也有助于团队的编码风格和形成规范。
Gin官方文档地址:https://gin-gonic.com/zh-cn/docs
安装
$ go get -u github.com/gin-gonic/gin
Gin使用
Hello,World
package main
import (
"github.com/gin-gonic/gin"
"github.com/thinkerou/favicon"
)
func main() {
// 创建一个服务
ginServer := gin.Default()
//配置favicon.ico
ginServer.Use(favicon.New("./favicon.ico"))
//访问地址:处理请求Request Response
ginServer.GET("/hello", func(context *gin.Context) {
context.JSON(200, gin.H{"msg": "hello,world"})
})
// 服务器端口
ginServer.Run(":8082")
}
http://localhost:8082/hello
返回html模版
templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>我的第一个GoWeb页面</title>
</head>
<body>
<h1>Hello,GoWeb</h1>
获取后端的数据为:
{{.msg}}
</body>
</html>
package main
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/thinkerou/favicon"
)
func main() {
// 创建一个服务
ginServer := gin.Default()
// 配置favicon.ico
ginServer.Use(favicon.New("./favicon.ico"))
// 加载templates下所有的静态页面
ginServer.LoadHTMLGlob("./templates/*")
//ginServer.LoadHTMLFiles("./templates/index.html")
// 响应一个页面给前端
ginServer.GET("/index", func(context *gin.Context) {
context.HTML(http.StatusOK, "index.html", gin.H{
"msg": "这是Go后台传递的数据",
})
})
// 服务器端口
ginServer.Run(":8082")
}
http://localhost:8082/index
html+css+js
├── favicon.ico
├── go.mod
├── go.sum
├── main.go
├── static
│ ├── css
│ │ └── style.css
│ └── js
│ └── common.js
└── templates
└── index.html
package main
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/thinkerou/favicon"
)
func main() {
// 创建一个服务
ginServer := gin.Default()
// 配置favicon.ico
ginServer.Use(favicon.New("./favicon.ico"))
// 加载templates下所有的静态页面
ginServer.LoadHTMLGlob("./templates/*")
//ginServer.LoadHTMLFiles("./templates/index.html")
// 加载static文件
ginServer.Static("/static","./static")
// 响应一个页面给前端
ginServer.GET("/index", func(context *gin.Context) {
context.HTML(http.StatusOK, "index.html", gin.H{
"msg": "这是Go后台传递的数据",
})
})
// 服务器端口
ginServer.Run(":8082")
}
templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>我的第一个GoWeb页面</title>
<link rel="stylesheet" href="/static/css/style.css">
<script src="/static/js/common.js"></script>
</head>
<body>
<h1>Hello,GoWeb</h1>
获取后端的数据为:
{{.msg}}
</body>
</html>
static/css/style.css
body{
background: aqua;
}
static/js/common.js
alert(1)
http://localhost:8082/index
获取查询参数
package main
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/thinkerou/favicon"
)
func main() {
// 创建一个服务
ginServer := gin.Default()
// 配置favicon.ico
ginServer.Use(favicon.New("./favicon.ico"))
// 接收前端传递过来的参数
// url?userId=123&username=foo
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,
})
})
// 服务器端口
ginServer.Run(":8082")
}
http://localhost:8082/user/info?userId=123&username=zhangsan
获取路径参数
package main
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/thinkerou/favicon"
)
func main() {
// 创建一个服务
ginServer := gin.Default()
// 配置favicon.ico
ginServer.Use(favicon.New("./favicon.ico"))
// 获取路径参数
// url/123/foo
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,
})
})
// 服务器端口
ginServer.Run(":8082")
}
http://localhost:8082/user/info/123/lisi
前端给后端传递json
package main
import (
"encoding/json"
"net/http"
"github.com/gin-gonic/gin"
"github.com/thinkerou/favicon"
)
func main() {
// 创建一个服务
ginServer := gin.Default()
// 配置favicon.ico
ginServer.Use(favicon.New("./favicon.ico"))
// 前端给后端传递json
ginServer.POST("/json", func(context *gin.Context) {
// request.body
data, _ := context.GetRawData()
var m map[string]interface{}
// 将 JSON 格式的数据转化为 Go 中的数据结构:第一个参数是要解码的 JSON 字符串的字节数组,第二个参数是一个指向接收解码结果的 Go 对象的指针。
_ = json.Unmarshal(data, &m)
context.JSON(http.StatusOK, m)
})
// 服务器端口
ginServer.Run(":8082")
}
$ curl -X POST -H "Content-Type: application/json" -d '{"key1": "value1", "key2": "value2"}' http://localhost:8082/json
表单
package main
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/thinkerou/favicon"
)
func main() {
// 创建一个服务
ginServer := gin.Default()
// 配置favicon.ico
ginServer.Use(favicon.New("./favicon.ico"))
// 加载templates下所有的静态页面
ginServer.LoadHTMLGlob("./templates/*")
//ginServer.LoadHTMLFiles("./templates/index.html")
// 响应一个页面给前端
ginServer.GET("/index", func(context *gin.Context) {
context.HTML(http.StatusOK, "index.html", gin.H{
})
})
// 表单提交
ginServer.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,
})
})
// 服务器端口
ginServer.Run(":8082")
}
templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>我的第一个GoWeb页面</title>
<link rel="stylesheet" href="/static/css/style.css">
<script src="/static/js/common.js"></script>
</head>
<body>
<h1>Hello,GoWeb</h1>
<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>
http://localhost:8082/index
重定向
package main
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/thinkerou/favicon"
)
func main() {
// 创建一个服务
ginServer := gin.Default()
// 配置favicon.ico
ginServer.Use(favicon.New("./favicon.ico"))
// 加载templates下所有的静态页面
ginServer.LoadHTMLGlob("./templates/*")
//ginServer.LoadHTMLFiles("./templates/index.html")
// 重定向 301
ginServer.GET("/test", func(context *gin.Context) {
context.Redirect(http.StatusMovedPermanently, "https://www.baidu.com")
})
// 服务器端口
ginServer.Run(":8082")
}
http://localhost:8082/test
404页面
package main
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/thinkerou/favicon"
)
func main() {
// 创建一个服务
ginServer := gin.Default()
// 配置favicon.ico
ginServer.Use(favicon.New("./favicon.ico"))
// 加载templates下所有的静态页面
ginServer.LoadHTMLGlob("./templates/*")
//ginServer.LoadHTMLFiles("./templates/index.html")
// NoRoute 404
ginServer.NoRoute(func(context *gin.Context) {
context.HTML(http.StatusNotFound, "404.html", nil)
})
// 服务器端口
ginServer.Run(":8082")
}
templates/404.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>404</title>
</head>
<body>
<h1>我的404页面</h1>
</body>
</html>
http://localhost:8082/aaaaaaa
路由组
package main
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/thinkerou/favicon"
)
func main() {
// 创建一个服务
ginServer := gin.Default()
// 配置favicon.ico
ginServer.Use(favicon.New("./favicon.ico"))
// 加载templates下所有的静态页面
ginServer.LoadHTMLGlob("./templates/*")
//ginServer.LoadHTMLFiles("./templates/index.html")
// 路由组
userGroup := ginServer.Group("/user")
{
userGroup.GET("/add", func(context *gin.Context) {
context.JSON(http.StatusOK, gin.H{
"msg": "ok",
})
})
userGroup.POST("/login", func(context *gin.Context) {
context.JSON(http.StatusOK, gin.H{
"msg": "ok",
})
})
userGroup.POST("/logout", func(context *gin.Context) {
context.JSON(http.StatusOK, gin.H{
"msg": "ok",
})
})
}
// 路由组
orderGroup := ginServer.Group("/order")
{
orderGroup.GET("/add", func(context *gin.Context) {
context.JSON(http.StatusOK, gin.H{
"msg": "ok",
})
})
orderGroup.DELETE("/delete", func(context *gin.Context) {
context.JSON(http.StatusOK, gin.H{
"msg": "ok",
})
})
}
// 服务器端口
ginServer.Run(":8082")
}
http://localhost:8082/user/add
http://localhost:8082/order/add
自定义Go语言中的中间件(拦截器)
即用于处理登陆授权、验证、分页、耗时统计等等
package main
import (
"log"
"github.com/gin-gonic/gin"
"github.com/thinkerou/favicon"
)
// 自定义Go中间件 拦截器
func myHandler() gin.HandlerFunc {
return func(context *gin.Context) {
// 通过自定义的中间件,设置的值,在后续处理只要调用了这个中间件的都可以拿到这里的参数
context.Set("userSession", "userId-1")
// 获取查询参数“username”的值
username := context.Query("username")
if username == "" || username == "zhangsan" {
// 如果username为空或是"zhangsan",则拦截请求并返回 403 状态码
context.AbortWithStatus(403)
return
}
context.Next() // 放行
}
}
func main() {
// 创建一个服务
ginServer := gin.Default()
// 配置favicon.ico
ginServer.Use(favicon.New("./favicon.ico"))
// 此时在进入下面方法之前就会先由myHandler()进行处理
ginServer.GET("/hello", myHandler(), func(context *gin.Context) {
// 取出中间件中的值,并后台打印
userSession := context.MustGet("userSession").(string)
log.Println("=====>", userSession)
// 获取查询参数“username”的值
username := context.Query("username")
context.JSON(200, gin.H{"msg": "hello, " + username})
})
// 服务器端口
ginServer.Run(":8082")
}
[GIN] 2023/04/23 - 00:52:06 | 403 | 4.117µs | ::1 | GET "/hello"
2023/04/23 00:52:17 =====> userId-1
[GIN] 2023/04/23 - 00:52:17 | 200 | 125.145µs | ::1 | GET "/hello?username=lisi"
[GIN] 2023/04/23 - 00:52:29 | 403 | 5.051µs | ::1 | GET "/hello?username=zhangsan"
http://localhost:8082/hello
http://localhost:8082/hello?username=lisi
http://localhost:8082/hello?username=zhangsan