最近在跟别人合作一个项目,由于对方不会用nginx,所以我得尝试用gin来代理静态页面。
gin虽然有代理静态页面的方法:Static(relativePath, root string)
,但是不符合我的需求。因为我一般会将静态页面分为多种,比如路由为"/“则为html页面,因为这样符合一般的访问习惯,但在gin中不能这么做,因为gin的路由是一个前缀树,如果把一个路由设置为”/",其他路由都会出错。
然而我在gin的issue里找到了一个库: “github.com/gin-contrib/static”,完美的解决了我的问题。
举个例子,假如我需要的路由为:
"/" => 前端页面
"/js/" => js文件
"/css/" => css文件
"/asset/img/" => 图片文件
则代码可以这样写
package main
import (
"github.com/gin-gonic/gin"
"github.com/gin-contrib/static"
)
func main() {
server := gin.Default()
server.Use(static.ServeRoot("/", "./static/html"))
server.Use(static.ServeRoot("/js", "./static/js"))
server.Use(static.ServeRoot("/css", "./static/css"))
server.Use(static.ServeRoot("/image", "./static/asset/image"))
if err := server.Run(":8080"); err != nil {
panic(err)
}
}
这个库的用法,主要是把serveRoot当作一个中间件,在每个请求之前都执行一遍,看看路径是否符合这个路由,如果符合,则返回这个静态资源,并结束这个请求。虽然性能上可能会有点问题,但是作为一个demo,这样做还是很方便的。
我的博客 blog.huining.tech