Skip to content
Static file handler for Gin
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.gitignore
LICENSE.md
README.md
go.mod
go.sum
static.go

README.md

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.

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"

If pngcrush is available it will be used to crush .png images

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 assets 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 /public 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.

You can’t perform that action at this time.