メモ置き場

echoで静的ファイルを配信する

ファイル指定

package main

import (
	"github.com/labstack/echo/v4"
)

func main() {
	e := echo.New()
	e.File("/static", "public/index.html")
	e.Logger.Fatal(e.Start(":8080"))
}
リクエストパスレスポンス
/staticpublic/index.htmlの内容
/static/404 Not Found

ディレクトリ指定

package main

import (
	"github.com/labstack/echo/v4"
)

func main() {
	e := echo.New()
	e.Static("/", "public")
	e.Logger.Fatal(e.Start(":8080"))
}
リクエストパスレスポンス
/static/static/への301 Moved Permanentlyリダイレクト
/static/public/index.htmlの内容
/static/index.htmlpublic/index.htmlの内容

fs.FS指定

package main

import (
	"embed"
	"github.com/labstack/echo/v4"
)

//go:embed public
var fs embed.FS

func main() {
	e := echo.New()
	e.StaticFS("/static", fs)
	e.Logger.Fatal(e.Start(":8080"))
}
リクエストパスレスポンス
/static/static/への301 Moved Permanentlyリダイレクト
/static/404 Not Found
/static/index.html404 Not Found
/static/public/static/public/への301 Moved Permanentlyリダイレクト
/static/publicpublic/index.htmlの内容
/static/public/index.htmlpublic/index.htmlの内容

Static middleware

package main

import (
	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
)

func main() {
	e := echo.New()
	e.Use(middleware.Static("public"))
	e.Logger.Fatal(e.Start(":8080"))
}
リクエストパスレスポンス
/public/index.htmlの内容
/index.htmlpublic/index.htmlの内容
package main

import (
	"embed"
	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
	"net/http"
)

//go:embed public
var fs embed.FS

func main() {
	e := echo.New()
	e.Use(middleware.StaticWithConfig(middleware.StaticConfig{
		Root:       "public",
		Filesystem: http.FS(fs),
	}))
	e.Logger.Fatal(e.Start(":8080"))
}
リクエストパスレスポンス
/public/index.htmlの内容
/index.htmlpublic/index.htmlの内容

参考