Last active
August 29, 2015 14:15
-
-
Save indraniel/93a9428073a8638fdae6 to your computer and use it in GitHub Desktop.
A rudimentary file and directory server
This file contains hidden or 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
/* 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