From a3166a87f077d5eeab7833cdbf5a6b804a707940 Mon Sep 17 00:00:00 2001 From: Lukas SP Date: Sun, 23 Aug 2020 16:22:20 +0200 Subject: [PATCH] Implement legacy hastebin support --- internal/web/web.go | 56 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/internal/web/web.go b/internal/web/web.go index 4b6be19..0fc0669 100644 --- a/internal/web/web.go +++ b/internal/web/web.go @@ -1,7 +1,10 @@ package web import ( + "encoding/json" "github.com/Lukaesebrot/pasty/internal/env" + "github.com/Lukaesebrot/pasty/internal/pastes" + "github.com/Lukaesebrot/pasty/internal/storage" v1 "github.com/Lukaesebrot/pasty/internal/web/controllers/v1" routing "github.com/fasthttp/router" "github.com/valyala/fasthttp" @@ -40,6 +43,11 @@ func Serve() error { } } + // Route the hastebin documents route if hastebin support is enabled + if env.Get("HASTEBIN_SUPPORT", "false") == "true" { + router.POST("/documents", hastebinSupportHandler) + } + // Serve the web server address := env.Get("WEB_ADDRESS", ":8080") return (&fasthttp.Server{ @@ -61,3 +69,51 @@ func frontendHandler() fasthttp.RequestHandler { } return fs.NewRequestHandler() } + +// hastebinSupportHandler handles the legacy hastebin requests +func hastebinSupportHandler(ctx *fasthttp.RequestCtx) { + // Define the paste content + var content string + switch string(ctx.Request.Header.ContentType()) { + case "text/plain": + content = string(ctx.PostBody()) + break + case "multipart/form-data": + content = string(ctx.FormValue("data")) + break + default: + ctx.SetStatusCode(fasthttp.StatusBadRequest) + ctx.SetBodyString("invalid content type") + return + } + + // Create the paste object + paste, err := pastes.Create(content) + if err != nil { + ctx.SetStatusCode(fasthttp.StatusInternalServerError) + ctx.SetBodyString(err.Error()) + return + } + + // Hash the deletion token + err = paste.HashDeletionToken() + if err != nil { + ctx.SetStatusCode(fasthttp.StatusInternalServerError) + ctx.SetBodyString(err.Error()) + return + } + + // Save the paste + err = storage.Current.Save(paste) + if err != nil { + ctx.SetStatusCode(fasthttp.StatusInternalServerError) + ctx.SetBodyString(err.Error()) + return + } + + // Respond with the paste key + jsonData, _ := json.Marshal(map[string]string{ + "key": paste.ID.String(), + }) + ctx.SetBody(jsonData) +}