go get -u github.com/gin-gonic/gin
一个简单的例子:
package main
import "github.com/gin-gonic/gin"
func main() {
//Default返回一个默认的路由引擎
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
//输出json结果给调用方
c.JSON(200, gin.H{
"message": "pong",
})
})
r.Run() // listen and serve on 0.0.0.0:8080
}
编译运行程序,打开浏览器,访问http://localhost:8080/ping页面显示:{"message":"pong"}
gin 的功能不只是简单输出 Json 数据。它是一个轻量级的 WEB 框架,支持 RestFull 风格 API,支持 GET,POST,PUT,PATCH,DELETE,OPTIONS 等 http 方法,支持文件上传,分组路由,Multipart/Urlencoded FORM,以及支持 JsonP,参数处理等等功能,这些都和 WEB 紧密相关,通过提供这些功能,使开发人员更方便地处理 WEB 业务。
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
// 静态资源加载,本例为css,js以及资源图片
router.StaticFS("/public", http.Dir("D:/goproject/src/github.com/ffhelicopter/tmm/website/static"))
router.StaticFile("/favicon.ico", "./resources/favicon.ico")
// Listen and serve on 0.0.0.0:80
router.Run(":80")
}
首先需要是生成一个 Engine,这是 gin 的核心,默认带有 Logger 和 Recovery 两个中间件。router := gin.Default()
StaticFile 是加载单个文件,而 StaticFS 是加载一个完整的目录资源:
func (group *RouterGroup) StaticFile(relativePath, filepath string) IRoutes
func (group *RouterGroup) StaticFS(relativePath string, fs http.FileSystem) IRoutes
http://localhost/public/images/logo.jpg图片加载正常。每次请求响应都会在服务端有日志产生,包括响应时间,加载资源名称,响应状态值等等。
package main
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"time"
"github.com/ffhelicopter/tmm/handler"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
// 静态资源加载,本例为css,js以及资源图片
router.StaticFS("/public", http.Dir("D:/goproject/src/github.com/ffhelicopter/tmm/website/static"))
router.StaticFile("/favicon.ico", "./resources/favicon.ico")
// 导入所有模板,多级目录结构需要这样写
router.LoadHTMLGlob("website/tpl/*/*")
// website分组
v := router.Group("/")
{
v.GET("/index.html", handler.IndexHandler)
v.GET("/add.html", handler.AddHandler)
v.POST("/postme.html", handler.PostmeHandler)
}
// router.Run(":80")
// 这样写就可以了,下面所有代码(go1.8+)是为了优雅处理重启等动作。
srv := &http.Server{
Addr: ":80",
Handler: router,
ReadTimeout: 30 * time.Second,
WriteTimeout: 30 * time.Second,
}
go func() {
// 监听请求
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("listen: %s\n", err)
}
}()
// 优雅Shutdown(或重启)服务
quit := make(chan os.Signal)
signal.Notify(quit, os.Interrupt) // syscall.SIGKILL
<-quit
log.Println("Shutdown Server ...")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Fatal("Server Shutdown:", err)
}
select {
case <-ctx.Done():
}
log.Println("Server exiting")
}
在动态站点实现中,引入 WEB 分组以及优雅重启这两个功能。WEB 分组功能可以通过不同的入口根路径来区别不同的模块,这里我们可以访问:http://localhost/index.html。如果新增一个分组,比如:v := router.Group("/login")
我们可以访问:http://localhost/login/xxxx,xxx 是我们在 v.GET 方法或 v.POST 方法中的路径。
// 导入所有模板,多级目录结构需要这样写
router.LoadHTMLGlob("website/tpl/*/*")
// website分组
v := router.Group("/")
{
v.GET("/index.html", handler.IndexHandler)
v.GET("/add.html", handler.AddHandler)
v.POST("/postme.html", handler.PostmeHandler)
}
router.LoadHTMLGlob("website/tpl/*/*")
比如 v.GET("/index.html", handler.IndexHandler),通过访问http://localhost/index.html这个 URL,实际由 handler.IndexHandler 来处理。而在 tmm 目录下的 handler 存放了 package handler 文件。在包里定义了 IndexHandler 函数,它使用了 index.html 模板。
func IndexHandler(c *gin.Context) {
c.HTML(http.StatusOK, "index.html", gin.H{
"Title": "作品欣赏",
})
}
<!DOCTYPE html>
<html>
<head>
{{template "header" .}}
</head>
<body>
<!--导航-->
<div class="feeds">
<div class="top-nav">
<a href="/index.tml" class="active">欣赏</a>
<a href="/add.html" class="add-btn">
<svg class="icon" aria-hidden="true">
<use xlink:href="#icon-add"></use>
</svg>
发布
</a>
</div>
<input type="hidden" id="showmore" value="{$showmore}">
<input type="hidden" id="page" value="{$page}">
<!--</div>-->
</div>
<script type="text/javascript">
var done = true;
$(window).scroll(function(){
var scrollTop = $(window).scrollTop();
var scrollHeight = $(document).height();
var windowHeight = $(window).height();
var showmore = $("#showmore").val();
if(scrollTop + windowHeight + 300 >= scrollHeight && showmore == 1 && done){
var page = $("#page").val();
done = false;
$.get("{:U('Product/listsAjax')}", { page : page }, function(json) {
if (json.rs != "") {
$(".feeds").append(json.rs);
$("#showmore").val(json.showmore);
$("#page").val(json.page);
done = true;
}
},'json');
}
});
</script>
<script src="//at.alicdn.com/t/font_ttszo9rnm0wwmi.js"></script>
</body>
</html>
在 index.html 模板中,通过 {{template "header" .}} 语句,嵌套了 header.html 模板。
{{ define "header" }}
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="format-detection" content="telephone=no,email=no">
<title>{{ .Title }}</title>
<link rel="stylesheet" href="/public/css/common.css">
<script src="/public/lib/jquery-3.1.1.min.js"></script>
<script src="/public/lib/jquery.cookie.js"></script>
<link href="/public/css/font-awesome.css?v=4.4.0" rel="stylesheet">
{{ end }}
{{ define "header" }} 让我们在模板嵌套时直接使用 header 名字,而在 index.html 中的 {{template "header" .}} 注意“.”,可以使参数嵌套传递,否则不能传递,比如这里的 Title。http://localhost/index.html,可以看到浏览器显示 Title 是“作品欣赏”,这个 Title 是通过 IndexHandler 来指定的。有关 IPFS: IPFS 本质上是一种内容可寻址、版本化、点对点超媒体的分布式存储、传输协议,目标是补充甚至取代过去 20 年里使用的超文本媒体传输协议(HTTP),希望构建更快、更安全、更自由的互联网时代。注意:由于在本人在发布到 github 的代码中,在处理图片上传的代码中,除了服务器存储外,还实现了 IPFS 发布存储,如果不需要 IPFS,请注释相关代码。
import "github.com/didip/tollbooth/limiter"包,在上面代码基础上增加如下语句:
//rate-limit 限流中间件
lmt := tollbooth.NewLimiter(1, nil)
lmt.SetMessage("服务繁忙,请稍后再试...")
v.GET("/index.html", LimitHandler(lmt), handler.IndexHandler)
当 F5 刷新刷新http://localhost/index.html页面时,浏览器会显示:服务繁忙,请稍后再试...tollbooth.LimitByKeys(lmt, []string{"127.0.0.1", "/"})
更多限流策略的配置,可以进一步github.com/didip/tollbooth/limiter了解。http://localhost/v1/user/1100000/这里对 v1.GET("/user/:id/*action", LimitHandler(lmt), api.GetUser) 进行了限流控制,所以如果频繁访问上面地址也将会有限制,这在 API 接口中非常有作用。
//CORS 局部CORS,可在路由中设置全局的CORS
c.Writer.Header().Add("Access-Control-Allow-Origin", "*")
package main
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"time"
"github.com/didip/tollbooth"
"github.com/didip/tollbooth/limiter"
"github.com/ffhelicopter/tmm/api"
"github.com/ffhelicopter/tmm/handler"
"github.com/gin-gonic/gin"
)
// 定义全局的CORS中间件
func Cors() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Add("Access-Control-Allow-Origin", "*")
c.Next()
}
}
func LimitHandler(lmt *limiter.Limiter) gin.HandlerFunc {
return func(c *gin.Context) {
httpError := tollbooth.LimitByRequest(lmt, c.Writer, c.Request)
if httpError != nil {
c.Data(httpError.StatusCode, lmt.GetMessageContentType(), []byte(httpError.Message))
c.Abort()
} else {
c.Next()
}
}
}
func main() {
gin.SetMode(gin.ReleaseMode)
router := gin.Default()
// 静态资源加载,本例为css,js以及资源图片
router.StaticFS("/public", http.Dir("D:/goproject/src/github.com/ffhelicopter/tmm/website/static"))
router.StaticFile("/favicon.ico", "./resources/favicon.ico")
// 导入所有模板,多级目录结构需要这样写
router.LoadHTMLGlob("website/tpl/*/*")
// 也可以根据handler,实时导入模板。
// website分组
v := router.Group("/")
{
v.GET("/index.html", handler.IndexHandler)
v.GET("/add.html", handler.AddHandler)
v.POST("/postme.html", handler.PostmeHandler)
}
// 中间件 golang的net/http设计的一大特点就是特别容易构建中间件。
// gin也提供了类似的中间件。需要注意的是中间件只对注册过的路由函数起作用。
// 对于分组路由,嵌套使用中间件,可以限定中间件的作用范围。
// 大致分为全局中间件,单个路由中间件和群组中间件。
// 使用全局CORS中间件。
// router.Use(Cors())
// 即使是全局中间件,在use前的代码不受影响
// 也可在handler中局部使用,见api.GetUser
//rate-limit 中间件
lmt := tollbooth.NewLimiter(1, nil)
lmt.SetMessage("服务繁忙,请稍后再试...")
// API分组(RESTFULL)以及版本控制
v1 := router.Group("/v1")
{
// 下面是群组中间的用法
// v1.Use(Cors())
// 单个中间件的用法
// v1.GET("/user/:id/*action",Cors(), api.GetUser)
// rate-limit
v1.GET("/user/:id/*action", LimitHandler(lmt), api.GetUser)
//v1.GET("/user/:id/*action", Cors(), api.GetUser)
// AJAX OPTIONS ,下面是有关OPTIONS用法的示例
// v1.OPTIONS("/users", OptionsUser) // POST
// v1.OPTIONS("/users/:id", OptionsUser) // PUT, DELETE
}
srv := &http.Server{
Addr: ":80",
Handler: router,
ReadTimeout: 30 * time.Second,
WriteTimeout: 30 * time.Second,
}
go func() {
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("listen: %s\n", err)
}
}()
// 优雅Shutdown(或重启)服务
// 5秒后优雅Shutdown服务
quit := make(chan os.Signal)
signal.Notify(quit, os.Interrupt) //syscall.SIGKILL
<-quit
log.Println("Shutdown Server ...")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Fatal("Server Shutdown:", err)
}
select {
case <-ctx.Done():
}
log.Println("Server exiting")
}
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有