Implement legacy hastebin support

This commit is contained in:
Lukas SP 2020-08-23 16:22:20 +02:00
parent cc150b82ac
commit a3166a87f0
1 changed files with 56 additions and 0 deletions

View File

@ -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)
}