Skip to content
Santekno.com | Level Up Your Engineering Skills
EN
📖 0%
04 Oct 2023 · 2 min read ·Article 63 / 119
Go

04 Learn About Serve File

IH
Ihsan Arif
Writer at Santekno · Backend Engineer

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.

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

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

go
1//go:embed resources
2var resources embed.FS

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

go
1router.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.

go
 1package main
 2
 3import (
 4	"embed"
 5	"io/fs"
 6	"net/http"
 7
 8	"github.com/julienschmidt/httprouter"
 9)
10
11//go:embed resources
12var resources embed.FS
13
14func main() {
15	router := httprouter.New()
16	directory, _ := fs.Sub(resources, "resources")
17
18	router.GET("/", SampleGetHandler)
19	router.POST("/", SamplePostHandler)
20	router.GET("/product/:id", GetUsedParamsHandler)
21	router.GET("/product/:id/items/:itemId", NamedParameterHandler)
22	router.GET("/images/*image", CatchAllParameterHandler)
23	router.ServeFiles("/files/*filepath", http.FS(directory))
24
25	server := http.Server{
26		Handler: router,
27		Addr:    "localhost:8080",
28	}
29
30	server.ListenAndServe()
31}

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.

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

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

bash
1➜  santekno-hugo git:(main) ✗ curl --location --request GET 'http://localhost:8080/files/hello.txt'
2Halo Santekno%           

Related Articles

💬 Comments