Serving the current directory over HTTP with Go
I've recently been updating a few lightweight static websites and have wanted to preview the changes locally.
Although I usually reach for python -mhttp.server
, it's a bit cumbersome to type, so I wanted something a little shorter. I was thinking of writing a script to make it quicker to type, when I thought - "what if I can do it quicker in Go"?
It turns out, it's blazingly fast to do so, in two lines(!) of code:
package main
import (
"log"
"net/http"
)
func main() {
http.Handle("/", http.FileServer(http.Dir(".")))
log.Fatal(http.ListenAndServe("127.0.0.1:8080", nil))
}
That's it! This allows you to serve the current directory that the built binary is executed in over HTTP.
I've wrapped this into a standalone tool just to make it easier to install and run, and I may end up adding some more (limited scope) functionality, while leaving it as lightweight as possible.