Skip to content

Instantly share code, notes, and snippets.

@jeddenlea
Created June 19, 2014 20:12
Show Gist options
  • Save jeddenlea/6a5da8b5cdf768d64b24 to your computer and use it in GitHub Desktop.
Save jeddenlea/6a5da8b5cdf768d64b24 to your computer and use it in GitHub Desktop.
Quick and dirty file server
package main
import (
"flag"
"log"
"net/http"
)
var (
flagLog = flag.Bool("log", false, "Log requests")
flagBind = flag.String("bind", ":9999", "Bind to address")
flagDir = flag.String("dir", ".", "Directory to serve")
)
type loggingHandler struct {
http.Handler
}
type loggingWriter struct {
http.ResponseWriter
code int
wh bool
}
func (l *loggingWriter) WriteHeader(code int) {
l.code = code
l.wh = true
l.ResponseWriter.WriteHeader(code)
}
func (l *loggingWriter) Write(p []byte) (int, error) {
if !l.wh {
l.WriteHeader(200)
}
return l.ResponseWriter.Write(p)
}
func (l loggingHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
lw := loggingWriter{ResponseWriter: w}
l.Handler.ServeHTTP(&lw, r)
log.Println(r.Host, r.RequestURI, lw.code)
}
func main() {
flag.Parse()
h := http.FileServer(http.Dir(*flagDir))
if *flagLog {
h = loggingHandler{h}
}
log.Fatal(http.ListenAndServe(*flagBind, h))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment