updown/web/paste.go
Nick Krichevsky 58bfe7729c Add route to get paste
Needs an actual template - it's totally XSS vulnerable at the moment
2019-03-17 17:40:47 -04:00

82 lines
1.7 KiB
Go

package web
import (
"database/sql"
"fmt"
"net/http"
"github.com/go-chi/chi"
"github.com/google/uuid"
"github.com/sirupsen/logrus"
)
const (
titleFormKey = "title"
bodyFormKey = "body"
)
func (server *Webserver) index(w http.ResponseWriter, req *http.Request) {
template, err := server.templates.Find("index.html")
if err != nil {
w.WriteHeader(500)
server.log(logrus.ErrorLevel, req, err)
return
}
w.Write(template)
}
func (server *Webserver) makePaste(w http.ResponseWriter, req *http.Request) {
title := req.PostFormValue(titleFormKey)
body := req.PostFormValue(bodyFormKey)
if len(title) == 0 || len(body) == 0 {
w.WriteHeader(400)
return
}
paster, err := server.pasteService.CreatePaste(title)
if err != nil {
w.WriteHeader(500)
server.log(logrus.ErrorLevel, req, err)
return
}
defer paster.Close()
_, err = paster.Write([]byte(body))
if err != nil {
w.WriteHeader(500)
server.log(logrus.ErrorLevel, req, err)
return
}
redirectURI := fmt.Sprintf("/paste/%s", paster.Paste.Handle)
http.Redirect(w, req, redirectURI, http.StatusSeeOther)
}
func (server *Webserver) getPaste(w http.ResponseWriter, req *http.Request) {
rawHandle := chi.URLParam(req, "handle")
handle, err := uuid.Parse(rawHandle)
if err != nil {
// If the handle doesn't parse, we won't ever be able to find the resource
w.WriteHeader(404)
server.log(logrus.InfoLevel, req, err)
return
}
paster, err := server.pasteService.GetPaste(handle)
if err == sql.ErrNoRows {
w.WriteHeader(404)
server.log(logrus.InfoLevel, req, err)
} else if err != nil {
w.WriteHeader(500)
server.log(logrus.ErrorLevel, req, err)
return
}
err = paster.Pipe(w)
if err != nil {
w.WriteHeader(500)
server.log(logrus.ErrorLevel, req, err)
return
}
}