mirror of
https://github.com/lus/pasty.git
synced 2023-08-10 21:13:09 +03:00
Implement basic web server structure and get paste endpoint
This commit is contained in:
47
internal/web/controllers/v1/pastes.go
Normal file
47
internal/web/controllers/v1/pastes.go
Normal file
@@ -0,0 +1,47 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"github.com/Lukaesebrot/pasty/internal/storage"
|
||||
"github.com/bwmarrin/snowflake"
|
||||
"github.com/fasthttp/router"
|
||||
"github.com/valyala/fasthttp"
|
||||
)
|
||||
|
||||
// InitializePastesController initializes the '/v1/pastes/*' controller
|
||||
func InitializePastesController(group *router.Group) {
|
||||
group.GET("/{id}", v1GetPaste)
|
||||
}
|
||||
|
||||
// v1GetPaste handles the 'GET /v1/pastes/{id}' endpoint
|
||||
func v1GetPaste(ctx *fasthttp.RequestCtx) {
|
||||
// Parse the ID
|
||||
id, err := snowflake.ParseString(ctx.UserValue("id").(string))
|
||||
if err != nil {
|
||||
ctx.SetStatusCode(fasthttp.StatusBadRequest)
|
||||
ctx.SetBodyString("invalid ID format")
|
||||
return
|
||||
}
|
||||
|
||||
// Retrieve the paste
|
||||
paste, err := storage.Current.Get(id)
|
||||
if err != nil {
|
||||
ctx.SetStatusCode(fasthttp.StatusInternalServerError)
|
||||
ctx.SetBodyString(err.Error())
|
||||
return
|
||||
}
|
||||
if paste == nil {
|
||||
ctx.SetStatusCode(fasthttp.StatusNotFound)
|
||||
ctx.SetBodyString("paste not found")
|
||||
return
|
||||
}
|
||||
|
||||
// Respond with the paste
|
||||
jsonData, err := json.Marshal(paste)
|
||||
if err != nil {
|
||||
ctx.SetStatusCode(fasthttp.StatusInternalServerError)
|
||||
ctx.SetBodyString(err.Error())
|
||||
return
|
||||
}
|
||||
ctx.SetBody(jsonData)
|
||||
}
|
29
internal/web/web.go
Normal file
29
internal/web/web.go
Normal file
@@ -0,0 +1,29 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"github.com/Lukaesebrot/pasty/internal/env"
|
||||
v1 "github.com/Lukaesebrot/pasty/internal/web/controllers/v1"
|
||||
routing "github.com/fasthttp/router"
|
||||
"github.com/valyala/fasthttp"
|
||||
)
|
||||
|
||||
// Serve serves the web server
|
||||
func Serve() error {
|
||||
// Create the router
|
||||
router := routing.New()
|
||||
|
||||
// Route the API endpoints
|
||||
apiRoute := router.Group("/api")
|
||||
{
|
||||
v1Route := apiRoute.Group("/v1")
|
||||
{
|
||||
v1.InitializePastesController(v1Route.Group("/pastes"))
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Route the paste endpoints
|
||||
|
||||
// Serve the web server
|
||||
address := env.Get("WEB_ADDRESS", ":8080")
|
||||
return fasthttp.ListenAndServe(address, router.Handler)
|
||||
}
|
Reference in New Issue
Block a user