Go

Static File Server

admin by @admin ADMIN
Jun 13, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`http.FileServer` serves a directory; combine with `http.StripPrefix` to mount it at a URL path. One line for the most common static-asset use case.
Go
Raw
package main

import (
    "log"
    "net/http"
)

func main() {
    mux := http.NewServeMux()

    // Serve ./public/ at /static/
    fs := http.FileServer(http.Dir("./public"))
    mux.Handle("/static/", http.StripPrefix("/static/", fs))

    // Serve a single specific file
    mux.HandleFunc("/favicon.ico", func(w http.ResponseWriter, r *http.Request) {
        http.ServeFile(w, r, "./public/favicon.ico")
    })

    mux.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) {
        w.Write([]byte("home page"))
    })

    log.Fatal(http.ListenAndServe(":8080", mux))
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.