package main import ( "html/template" "log" "net/http" "strings" ) type TemplateHandler struct { handler http.Handler } func (t *TemplateHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Header().Set("Server", "uhttpd") // We use our custom handler to prettify directories. Files are served via default. if !strings.HasSuffix(r.URL.Path, "/") { t.handler.ServeHTTP(w, r) return } rec := NewRecorder() defer rec.Body.Reset() // passing the recorder instead of the real ResponseWriter t.handler.ServeHTTP(rec, r) // let the standard lib handle all the caching if rec.Code > 300 && rec.Code < 400 { log.Println("Code: ", rec.Code) t.handler.ServeHTTP(w, r) return } // we copy the original headers first for k, v := range rec.Header() { w.Header()[k] = v } // not found if rec.Code == 404 { w.Header().Set("Content-Type", "text/html") w.WriteHeader(404) tmpl := template.New("404") tmpl, err := tmpl.Parse(get404()) if err != nil { log.Println(err.Error()) w.WriteHeader(500) w.Write([]byte(err.Error())) return } err = tmpl.Execute(w, struct{ URL string }{URL: r.URL.Path}) if err != nil { log.Println(err.Error()) w.WriteHeader(500) w.Write([]byte(err.Error())) return } return } // we serve a file instead of a html page if !strings.Contains(w.Header().Get("Content-Type"), "text/html") { w.Write(rec.Body.Bytes()) return } data := rec.Body.String() // we serve the directoy page if strings.HasPrefix(data, "
") {
		execTemplate(w, r, data)
	} else {
		w.Write(rec.Body.Bytes())
	}
}

func execTemplate(w http.ResponseWriter, r *http.Request, data string) {
	data = strings.Replace(data, "
", "", 1)
	data = strings.Replace(data, "
", "", 1) data = strings.Replace(data, "", "
", -1) tmpl := template.New("page") tmpl, err := tmpl.Parse(getTemplate()) if err != nil { log.Println(err.Error()) w.WriteHeader(500) w.Write([]byte(err.Error())) return } err = tmpl.Execute(w, struct { Data template.HTML URL string }{Data: template.HTML(data), URL: r.URL.Path}) if err != nil { log.Println(err) } } func getTemplate() string { return ` {{.URL}}


{{.URL}}

{{if ne .URL "/"}} .. (up a dir)

{{end}} {{.Data}}
` } func get404() string { return ` Not Found - {{.URL}}

Not Found - {{.URL}}

Please check for typos in your url.

Go back to root

` } func getUpload() string { return ` Upload Form

Upload Form

You are going to upload a file. Here you can search to add it.


` } func getUploaded() string { return ` Uploaded {{.File}}

Uploaded!

{{.File}} was successfull uploaded.

Back to root

` }