Skip to content

Instantly share code, notes, and snippets.

@indraniel
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save indraniel/93a9428073a8638fdae6 to your computer and use it in GitHub Desktop.
Save indraniel/93a9428073a8638fdae6 to your computer and use it in GitHub Desktop.
A rudimentary file and directory server
/* See other alternatives as well:
https://github.com/rif/spark
https://github.com/mholt/caddy
https://github.com/GokulSrinivas/go-http
*/
package main
import (
"flag"
"fmt"
"log"
"net/http"
"os"
"path/filepath"
)
func main() {
portPtr := flag.Int("p", 9090, "port to serve on")
hostPtr := flag.String("h", "localhost", "hostname to use")
filePtr := flag.String("f", "", "a particular file to serve")
logPtr := flag.Bool("l", false, "display server access logs")
flag.Parse()
addr := fmt.Sprintf("%s:%d", *hostPtr, *portPtr)
if *filePtr != "" {
base := filepath.Base(*filePtr)
url_pattern := "/" + base
http.HandleFunc(url_pattern, FileHandler(*filePtr))
log.Println("Serving file ", *filePtr)
log.Printf("Please visit 'http://%s/%s' \n", addr, base)
} else {
dir := GetServeDir()
http.Handle("/", http.FileServer(http.Dir(dir)))
log.Println("Serving directory ", dir)
log.Printf("Please visit 'http://%s/' \n", addr)
}
if *logPtr {
log.Fatal(http.ListenAndServe(addr, Log(http.DefaultServeMux)))
} else {
log.Fatal(http.ListenAndServe(addr, nil))
}
}
func FileHandler(file string) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, file)
}
}
func GetServeDir() (dir string) {
if flag.NArg() < 1 {
cwd, err := os.Getwd()
if err != nil {
msg := "Please provide a directory argument to serve!"
log.Fatal(msg)
}
dir = cwd
} else {
dir = flag.Arg(0)
}
return dir
}
func Log(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("%s %s %s", r.RemoteAddr, r.Method, r.URL)
handler.ServeHTTP(w, r)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment