updown/web/paste.go

97 lines
2.0 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"
fileNameFormKey = "filename"
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) makePastes(w http.ResponseWriter, req *http.Request) {
title := req.PostFormValue(titleFormKey)
if len(title) == 0 {
fmt.Println("here")
w.WriteHeader(400)
return
}
fileMap, fileNames, err := makeFileMap(req.PostForm)
if err == errInvalidPasteForm {
w.WriteHeader(400)
return
} else if err != nil {
w.WriteHeader(500)
server.log(logrus.ErrorLevel, req, err)
return
}
clumper, err := server.pasteService.CreatePastes(title, fileNames)
if err != nil {
w.WriteHeader(500)
server.log(logrus.ErrorLevel, req, err)
return
}
defer clumper.Close()
for i, paster := range clumper.Pasters {
fileName := fileNames[i]
fileBody := fileMap[fileName]
_, err = paster.Write([]byte(fileBody))
if err != nil {
w.WriteHeader(500)
server.log(logrus.ErrorLevel, req, err)
return
}
}
// TODO: Display the clump
w.Write(clumper.Clump.Handle[:])
}
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
}
}