Sushi/types.go

80 lines
1.8 KiB
Go

package sushi
import (
"encoding/json"
"github.com/valyala/fasthttp"
)
type Ctx struct {
*fasthttp.RequestCtx
}
type Handler func(ctx Ctx)
type Middleware func(ctx Ctx, next func())
// SendHTML sends an HTML response
func (ctx Ctx) SendHTML(html string) {
ctx.SetContentType("text/html; charset=utf-8")
ctx.SetBodyString(html)
}
// SendText sends a plain text response
func (ctx Ctx) SendText(text string) {
ctx.SetContentType("text/plain; charset=utf-8")
ctx.SetBodyString(text)
}
// SendJSON sends a JSON response
func (ctx Ctx) SendJSON(data any) error {
jsonData, err := json.Marshal(data)
if err != nil {
ctx.SetStatusCode(fasthttp.StatusInternalServerError)
ctx.SetBodyString("Internal Server Error")
return err
}
ctx.SetContentType("application/json")
ctx.SetBody(jsonData)
return nil
}
// SendStatus sends only a status code
func (ctx Ctx) SendStatus(statusCode int) {
ctx.SetStatusCode(statusCode)
}
// SendError sends an error response with status code
func (ctx Ctx) SendError(statusCode int, message string) {
ctx.SetStatusCode(statusCode)
ctx.SetContentType("text/plain; charset=utf-8")
ctx.SetBodyString(message)
}
// Redirect sends a redirect response
func (ctx Ctx) Redirect(url string, statusCode ...int) {
code := fasthttp.StatusFound
if len(statusCode) > 0 {
code = statusCode[0]
}
ctx.RequestCtx.Redirect(url, code)
}
// SendFile serves a file
func (ctx Ctx) SendFile(filePath string) {
fasthttp.ServeFile(ctx.RequestCtx, filePath)
}
// SendBytes sends raw bytes with optional content type
func (ctx Ctx) SendBytes(data []byte, contentType ...string) {
if len(contentType) > 0 {
ctx.SetContentType(contentType[0])
}
ctx.SetBody(data)
}
// SendNoContent sends a 204 No Content response
func (ctx Ctx) SendNoContent() {
ctx.SetStatusCode(fasthttp.StatusNoContent)
}