programming

04 Learn About Serve File

Understanding File Server

In the material Creating Golang Web. So the Router also supports serving static files using the ServeFiles(Path, FileSystem) function where in Path we have to use Catch All Parameters. Meanwhile, in FileSystem you can manually load it from a folder or use Golang Embed as we discussed in the previous material.

Different from creating a handler, to create a serve file we need to create a directory path first so that it can be read by the system by adding the code below to the file. main.go.

directory, _ := fs.Sub(resources, "resources")

Read folders using embedded by creating global variables that can later be used in all projects.

//go:embed resources
var resources embed.FS

Then we add the router path where the folders and files can be read by the router.

router.ServeFiles("/files/*filepath", http.FS(directory))

Also make sure that the folder contains files because we are using go:embed so there is validation from Golang that if the folder is empty then the program will not run.

If you want to see the entire code in the main.go file it will be like below.

package main

import (
	"embed"
	"io/fs"
	"net/http"

	"github.com/julienschmidt/httprouter"
)

//go:embed resources
var resources embed.FS

func main() {
	router := httprouter.New()
	directory, _ := fs.Sub(resources, "resources")

	router.GET("/", SampleGetHandler)
	router.POST("/", SamplePostHandler)
	router.GET("/product/:id", GetUsedParamsHandler)
	router.GET("/product/:id/items/:itemId", NamedParameterHandler)
	router.GET("/images/*image", CatchAllParameterHandler)
	router.ServeFiles("/files/*filepath", http.FS(directory))

	server := http.Server{
		Handler: router,
		Addr:    "localhost:8080",
	}

	server.ListenAndServe()
}

We will try to test using cURL. Make sure the files in the folder the router is targeting are available so the data can be opened.

curl --location --request GET 'http://localhost:8080/files/hello.txt'

So if you execute cURL you will see results like this.

➜  santekno-hugo git:(main) ✗ curl --location --request GET 'http://localhost:8080/files/hello.txt'
Halo Santekno%           
comments powered by Disqus