Static Files plays a very important role in web development. Static Files like Images, CSS, JS, etc makes our website beautiful and interactive. In this blog, we will learn how to Serve Static files in Golang HTTP Server.
In the previous blog we learned about Golang templates, we will use the same template with a slight variation.
Serve Static Files Project Hierarchy
The Static directory has all the static files like the CSS file and the images. The template has an HTML file that will be used as a template in Golang.
If you don’t know about Templates in Golang, a must-read to understand it more clearly.
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/resources/css/style.css">
<title>Go Template</title>
</head>
<body>
<h1 class="title">Hello, {{.Name}}</h1>
<img src="/resources/images/gopher.png">
<p>Your College name is {{.College}}</p>
<p>Your ID is {{.RollNumber}}</p>
</body>
</html>
This time a CSS File is linked to the HTML file and an image is served.
Static CSS File
.title {
color: blue;
}
Serve Static Files using Golang FileServer
fileServer := http.FileServer(http.Dir("./Static"))
http.Handle("/resources/", http.StripPrefix("/resources", fileServer))
These are two lines of code that are added to the main function of the Go file.
The Golang FileServer takes the Directory of the system which is to be served over HTTP and returns a Handler.
Golang StripPrefix
FileServer’s returned Handler is then used in the StripPrefix()
function which strips the passed string from the URL and also returns a Handler. The StripPrefix()
is used for security purposes.
StripPrefix’s returned Handler is then handled by a URL.
$ go run serve-static-files.go
Output:
Golang FileServer Example
package main
import (
"html/template"
"log"
"net/http"
)
const (
Host = "localhost"
Port = "8080"
)
type Student struct {
Name string
College string
RollNumber int
}
func renderTemplate(w http.ResponseWriter, r *http.Request) {
student := Student{
Name: "GB",
College: "GolangBlogs",
RollNumber: 1,
}
parsedTemplate, _ := template.ParseFiles("Template/index.html")
err := parsedTemplate.Execute(w, student)
if err != nil {
log.Println("Error executing template :", err)
return
}
}
func main() {
fileServer := http.FileServer(http.Dir("./Static"))
http.Handle("/resources/", http.StripPrefix("/resources", fileServer))
http.HandleFunc("/", renderTemplate)
err := http.ListenAndServe(Host+":"+Port, nil)
if err != nil {
log.Fatal("Error Starting the HTTP Server :", err)
return
}
}
Learn more about Serving Static Files in Golang using FileServer from Golang.org.