Create basic gopaste web app
This commit is contained in:
commit
17ca93210b
6
editor.html
Normal file
6
editor.html
Normal file
@ -0,0 +1,6 @@
|
||||
<h1>gopaste</h1>
|
||||
|
||||
<form action="/create" method="post">
|
||||
<textarea name="stuff"></textarea>
|
||||
<input type="submit" value="Post" />
|
||||
</form>
|
69
paste.go
Normal file
69
paste.go
Normal file
@ -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)
|
||||
}
|
Loading…
Reference in New Issue
Block a user