Created
June 8, 2011 09:26
-
-
Save fudanchii/1014091 to your computer and use it in GitHub Desktop.
web server example for serving static file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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