Skip to content

Instantly share code, notes, and snippets.

@hmmftg
Forked from paulmach/serve.go
Last active November 29, 2024 09:36
Show Gist options
  • Save hmmftg/a3d64a7ab148ea26443bbfd4c3913899 to your computer and use it in GitHub Desktop.
Save hmmftg/a3d64a7ab148ea26443bbfd4c3913899 to your computer and use it in GitHub Desktop.
Simple Static File Server in Go
/*
Serve is a very simple static file server in go
Usage:
-p="8100": port to serve on
-d=".": the directory of static files to host
-b="/": the base URL to host
Navigating to http://localhost:8100 will display the index.html or directory
listing file.
*/
package main
import (
"flag"
"log"
"net/http"
"path/filepath"
"time"
)
var (
path = flag.String("d", ".", "path to the folder to serve. Defaults to the current folder")
port = flag.String("p", "8080", "port to serve on. Defaults to 8080")
basePath = flag.String("b", "/", "base url to serve on. Defaults to /")
)
func main() {
flag.Parse()
dirname, err := filepath.Abs(*path)
if err != nil {
log.Fatalf("Could not get absolute path to directory: %s: %s", dirname, err.Error())
}
log.Printf("Serving %s on port %s on url: %s", dirname, *port, *basePath)
fs := http.FileServer(http.Dir(dirname))
http.Handle(*basePath, http.StripPrefix(*basePath, fs))
srv := http.Server{
Addr: ":" + *port,
ReadTimeout: 1 * time.Second,
WriteTimeout: 1 * time.Second,
IdleTimeout: 30 * time.Second,
ReadHeaderTimeout: 2 * time.Second,
}
err = srv.ListenAndServe()
if err != nil {
log.Fatalf("Could not serve directory: %s: %s", dirname, err.Error())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment