gin-static
Static file serving for Gin. Compress assets such as .js
, .css
using gzip
.
All static assets are also served with proper cache control headers.
Its basically a simple Go extension for those who dont want to use a bundler.
Usage
Download and install:
go get github.com/raggaer/gin-static
Import on your code and start using it:
import "github.com/raggaer/gin-static"
Example
package main
import "github.com/gin-gonic/gin"
func main() {
// Load and compile static assets
// You can now access static.AssetMap that contains
// All compiled static files
static.LoadStaticAssets("public")
// Create gin router
router := gin.Default()
// Set asset func
router.SetFuncMap(template.FuncMap{
"asset": static.Asset,
})
// Declare our static path
router.GET("/static/*filepath", static.ServeStaticFiles)
router.Run(":8080")
}
On your templates you can access the compiled assets using the asset
function:
<html>
<head>
<title>Test</title>
</head>
<body>
<h2>Hello World!</h2>
</body>
<script src="{{ asset "/public/js/test.js" }}"></script>
</html>
About
gin-static
will load all your static files, minify them (.css
and .js
files) and gzip them.
You can later access the files using the variable AssetMap
(contains all loaded static files).
You can also access the static files on your .html
templates, first you need to declare the provided Asset
function
on your gin router func map.
While running on development mode, you should add a static handler route, so you dont need to recompile the static folder.
The {{ asset }}
function will check if gin is on debug mode, and return a path using the path you provided so you should declare the following router
to be able to work on development mode:
if gin.Mode() == gin.DebugMode {
r.Static("/public", "public")
}
If you ever make changes to your static files, you will need to restart your application,
you could use this as a separate server just to serve static files
License
gin-static
is licensed under the MIT license.