Skip to content

soulteary/gin-static

This branch is 61 commits ahead of, 52 commits behind gin-contrib/static:master.

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Dec 21, 2024
a5f515c · Dec 21, 2024
Nov 27, 2024
Dec 21, 2024
Nov 27, 2024
Mar 15, 2021
Jan 31, 2024
Jun 24, 2024
Sep 10, 2024
Dec 13, 2016
Apr 6, 2024
Jan 3, 2024
Jun 24, 2024
Dec 21, 2024
Dec 21, 2024
Apr 6, 2024
Jun 24, 2024
Mar 13, 2024
Jun 24, 2024

Repository files navigation

Gin Static Middleware

Run Tests codecov Go Report Card GoDoc

No Security Error, No uncovered function, No obsolete code.

  • Supercharged static middleware: seamlessly support local files and embedded filesystem for an unparalleled lightning-fast experience.
  • Break free from historical burdens and embrace the new era of Go 1.22. With 100% code coverage, enjoy the perfect blend of quality and performance!

Quick Start

Download and Import

Download and install it:

go get github.com/soulteary/gin-static

Import it in your code:

import "github.com/soulteary/gin-static"

Example

See the example

Serve Local Files

package main

import (
	"log"

	static "github.com/soulteary/gin-static"
	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()

	// if Allow DirectoryIndex
	// r.Use(static.Serve("/", static.LocalFile("./public", true)))
	// set prefix
	// r.Use(static.Serve("/static", static.LocalFile("./public", true)))

	r.Use(static.Serve("/", static.LocalFile("./public", false)))

	r.GET("/ping", func(c *gin.Context) {
		c.String(200, "test")
	})

	// Listen and Server in 0.0.0.0:8080
	if err := r.Run(":8080"); err != nil {
		log.Fatal(err)
	}
}

Serve Embed folder

package main

import (
	"embed"
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
)

//go:embed public
var EmbedFS embed.FS

func main() {
	r := gin.Default()

	// method 1: use as Gin Router
	// trim embedfs path `public/page`, and use it as url path `/`
	// r.GET("/", static.ServeEmbed("public/page", EmbedFS))

	// method 2: use as middleware
	// trim embedfs path `public/page`, the embedfs path start with `/`
	// r.Use(static.ServeEmbed("public/page", EmbedFS))

	// method 2.1: use as middleware
	// trim embedfs path `public/page`, the embedfs path start with `/public/page`
	// r.Use(static.ServeEmbed("", EmbedFS))

	// method 3: use as manual
	// trim embedfs path `public/page`, the embedfs path start with `/public/page`
	// staticFiles, err := static.EmbedFolder(EmbedFS, "public/page")
	// if err != nil {
	// 	log.Fatalln("initialization of embed folder failed:", err)
	// } else {
	// 	r.Use(static.Serve("/", staticFiles))
	// }

	r.GET("/ping", func(c *gin.Context) {
		c.String(200, "test")
	})

	r.NoRoute(func(c *gin.Context) {
		fmt.Printf("%s doesn't exists, redirect on /\n", c.Request.URL.Path)
		c.Redirect(http.StatusMovedPermanently, "/")
	})

	// Listen and Server in 0.0.0.0:8080
	r.Run(":8080")
}

Languages

  • Go 91.7%
  • Shell 5.2%
  • HTML 3.1%