hakk

software development, devops, and other drivel
Tree lined path

A quick HTTP file server example in Go

Basic example to serve directory.

package main

import (
    "flag"
    "fmt"
    "log"
    "net/http"
)

func main() {
    // Simple static webserver:
    pathPtr := flag.String("d", ".", "Directory path to serve")
    portPtr := flag.String("p", "8080", "Port to listen on")
    interfacePtr := flag.String("i", "", "Interface to listen on (default all)")
    flag.Parse()
    log.Printf("Serving %s on %s:%s", *pathPtr, *interfacePtr, *portPtr)
    err := http.ListenAndServe(fmt.Sprintf("%s:%s", *interfacePtr, *portPtr), http.FileServer(http.Dir(*pathPtr)))
    if err != nil {
        log.Fatal(err)
    }
}

Example with ability to set custom headers

package main

import (
    "flag"
    "fmt"
    "log"
    "net/http"
)

func main() {
    // Simple static webserver:
    pathPtr := flag.String("d", ".", "Directory path to serve")
    portPtr := flag.String("p", "8080", "Port to listen on")
    interfacePtr := flag.String("i", "", "Interface to listen on (default all)")
    flag.Parse()
    log.Printf("Serving %s on %s:%s", *pathPtr, *interfacePtr, *portPtr)
    fs := http.FileServer(http.Dir(*pathPtr))
    err := http.ListenAndServe(fmt.Sprintf("%s:%s", *interfacePtr, *portPtr), customHeaders(fs))
    if err != nil {
        log.Fatal(err)
    }
}

func customHeaders(fs http.Handler) http.HandlerFunc {
    // found at https://stackoverflow.com/a/65905091
    return func(w http.ResponseWriter, r *http.Request) {
        // add headers etc here
        // return if you do not want the FileServer handle a specific request
        w.Header().Set("Cache-Control", "no-cache")
        w.Header().Set("x-server", "hello, world!")
        fs.ServeHTTP(w, r)
    }
}