Serve Static Files in Golang Using FileServer

Share this blog with others!

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

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.


<!DOCTYPE html>
<html lang="en">

    <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>

    <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>



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


Serve Static Files in Golang

Golang FileServer Example

package main

import (

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)

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)

Learn more about Serving Static Files in Golang using FileServer from

4.3 3 votes
Article Rating

Share this blog with others!
Notify of
Inline Feedbacks
View all comments
Scroll to Top