From 17ca93210b89a03b46fe61561de137369c560e17 Mon Sep 17 00:00:00 2001 From: Matt Baer Date: Thu, 29 Nov 2018 09:57:07 -0500 Subject: [PATCH] Create basic gopaste web app --- editor.html | 6 +++++ paste.go | 69 +++++++++++++++++++++++++++++++++++++++++++++++++++++ post.html | 3 +++ 3 files changed, 78 insertions(+) create mode 100644 editor.html create mode 100644 paste.go create mode 100644 post.html diff --git a/editor.html b/editor.html new file mode 100644 index 0000000..a82dd87 --- /dev/null +++ b/editor.html @@ -0,0 +1,6 @@ +

gopaste

+ +
+ + +
diff --git a/paste.go b/paste.go new file mode 100644 index 0000000..c48dc73 --- /dev/null +++ b/paste.go @@ -0,0 +1,69 @@ +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) + + 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) +} diff --git a/post.html b/post.html new file mode 100644 index 0000000..bff8808 --- /dev/null +++ b/post.html @@ -0,0 +1,3 @@ +

gopaste

+ +
{{.}}