Skip to content

Instantly share code, notes, and snippets.

@fudanchii
Created June 8, 2011 09:26
Show Gist options
  • Save fudanchii/1014091 to your computer and use it in GitHub Desktop.
Save fudanchii/1014091 to your computer and use it in GitHub Desktop.
web server example for serving static file
package main
import (
"http"
"runtime"
"log"
"flag"
"os"
)
var (
path = flag.String("root", "/var/www/", "`-root='/var/www/'`. Set root directory, use absolute path.")
stat = flag.Bool("stat", false, "`-stat=true` or `-stat=false`. Show memory stats to stdout.")
help = flag.Bool("help", false, "`-help`. Show this message.")
)
func memStat(label string) {
log.Printf("\nMem Stat %s:\nheapAlloc: %d | footprint: %d\n\n",
label, runtime.MemStats.HeapAlloc, runtime.MemStats.Sys)
}
func handler(w http.ResponseWriter, r *http.Request) {
fname := "index.html"
if len(r.URL.Path) > 1 {
fname = r.URL.Path[1:]
}
ff := *path + fname
http.ServeFile(w, r, ff)
if *stat {
go memStat(fname)
}
w = nil
go runtime.GC()
}
func main() {
flag.Parse()
if *help {
flag.Usage()
os.Exit(0)
}
http.HandleFunc("/", handler)
http.ListenAndServe(":5050", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment