package main import ( "crypto/md5" "encoding/base64" "html/template" "io/ioutil" "log" "net/http" ) func main() { // Take user input, save it http.HandleFunc("/create", createPost) // Retrieve that, display it http.HandleFunc("/post/", viewPost) // Show an editor http.HandleFunc("/", viewEditor) log.Print("Listening...") log.Fatal(http.ListenAndServe(":8888", nil)) } func viewPost(w http.ResponseWriter, r *http.Request) { log.Print(r.URL.Path) id := r.URL.Path[len("/post/"):] data, err := ioutil.ReadFile(id + ".txt") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } t, err := template.ParseFiles("post.html") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } t.Execute(w, string(data)) } func createPost(w http.ResponseWriter, r *http.Request) { log.Print(r.URL.Path) data := r.FormValue("stuff") h := md5.New() idHash := h.Sum([]byte(data)) id := base64.StdEncoding.EncodeToString(idHash)[:20] err := ioutil.WriteFile(id+".txt", []byte(data), 0600) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } http.Redirect(w, r, "/post/"+id, http.StatusFound) } func viewEditor(w http.ResponseWriter, r *http.Request) { log.Print(r.URL.Path) // Display editor t, err := template.ParseFiles("editor.html") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } t.Execute(w, nil) }