package main import ( "fmt" "log" "net/http" "os" "html/template" "flag" ) var tmpl *template.Template func handleGet( w http.ResponseWriter, r *http.Request) { path := r.URL.Path[1:] if path == "" { path = "." } fmt.Printf("Trying to get [%s]\n", r.URL.Path[1:]) stat, err := os.Stat(path) switch { case err != nil || stat == nil : if os.IsNotExist(err) { w.WriteHeader(http.StatusNotFound) fmt.Fprintln(w, "File not found") fmt.Fprintln(w, "") fmt.Fprintln(w, "Sry bro") return } case stat.IsDir() : // If it's a collection list return the list of the collection type Entry struct { Name string Size int } var files []Entry f, err := os.Open(path) if err != nil { w.WriteHeader(http.StatusNotFound) fmt.Fprintln(w, "File not found") fmt.Fprintln(w, "") fmt.Fprintln(w, "Sry bro") return } fileInfo, err := f.Readdir(-1) f.Close() if err != nil { w.WriteHeader(http.StatusNotFound) fmt.Fprintln(w, "File not found") fmt.Fprintln(w, "") fmt.Fprintln(w, "Sry bro") } for _, file := range fileInfo { files = append(files, Entry{file.Name(), 0}) } type Collection struct { Name string ListEntries []Entry } tmpl.Execute(w, Collection{ "Title" , files}) case stat.Mode().IsRegular(): http.ServeFile(w, r, r.URL.Path[1:]) default: } } func handlePost( w http.ResponseWriter, r *http.Request) { } func handleDelete( w http.ResponseWriter, r *http.Request) { } func handlePut( w http.ResponseWriter, r *http.Request) { } func handleMethod( w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodGet: handleGet(w, r) case http.MethodPost: handlePost(w, r) case http.MethodPut: handlePut(w, r) case http.MethodDelete: // Remove the record. handleDelete(w, r) default: w.WriteHeader(http.StatusTeapot) fmt.Fprintln(w, "Sry, i'm a teapot >///<") fmt.Fprintln(w, "") fmt.Fprintln(w, "Here's some tea. 🍵") } } func main() { var dir string const ( defaultDir = "." usageDir = "the directory to serve" ) flag.StringVar(&dir, "directory", defaultDir, usageDir) flag.StringVar(&dir, "d", defaultDir, usageDir+" (shorthand)") flag.Parse() if dir == "" { dir = defaultDir } tmpl = template.Must(template.ParseFiles("dir.html")) fmt.Println("Launch server") http.HandleFunc("/", handleMethod) log.Fatal(http.ListenAndServe(":8080", nil)) fmt.Println("Bye bye") }