mirror of
https://github.com/lus/pasty.git
synced 2023-08-10 21:13:09 +03:00
Implement rate limiting
This commit is contained in:
56
internal/web/controllers/v1/hastebin_support.go
Normal file
56
internal/web/controllers/v1/hastebin_support.go
Normal file
@ -0,0 +1,56 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"github.com/Lukaesebrot/pasty/internal/pastes"
|
||||
"github.com/Lukaesebrot/pasty/internal/storage"
|
||||
"github.com/valyala/fasthttp"
|
||||
)
|
||||
|
||||
// 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)
|
||||
}
|
@ -6,14 +6,15 @@ import (
|
||||
"github.com/Lukaesebrot/pasty/internal/storage"
|
||||
"github.com/bwmarrin/snowflake"
|
||||
"github.com/fasthttp/router"
|
||||
limitFasthttp "github.com/ulule/limiter/v3/drivers/middleware/fasthttp"
|
||||
"github.com/valyala/fasthttp"
|
||||
)
|
||||
|
||||
// InitializePastesController initializes the '/v1/pastes/*' controller
|
||||
func InitializePastesController(group *router.Group) {
|
||||
group.GET("/{id}", v1GetPaste)
|
||||
group.POST("", v1PostPaste)
|
||||
group.DELETE("/{id}", v1DeletePaste)
|
||||
func InitializePastesController(group *router.Group, rateLimiterMiddleware *limitFasthttp.Middleware) {
|
||||
group.GET("/{id}", rateLimiterMiddleware.Handle(v1GetPaste))
|
||||
group.POST("", rateLimiterMiddleware.Handle(v1PostPaste))
|
||||
group.DELETE("/{id}", rateLimiterMiddleware.Handle(v1DeletePaste))
|
||||
}
|
||||
|
||||
// v1GetPaste handles the 'GET /v1/pastes/{id}' endpoint
|
||||
|
Reference in New Issue
Block a user