add send helpers

This commit is contained in:
Sky Johnson 2025-08-15 14:37:09 -05:00
parent b7822c1b50
commit 8944c20394

72
send.go Normal file
View File

@ -0,0 +1,72 @@
package sushi
import (
"encoding/json"
"github.com/valyala/fasthttp"
)
// SendHTML sends an HTML response
func SendHTML(ctx Ctx, html string) {
ctx.SetContentType("text/html; charset=utf-8")
ctx.SetBodyString(html)
}
// SendText sends a plain text response
func SendText(ctx Ctx, text string) {
ctx.SetContentType("text/plain; charset=utf-8")
ctx.SetBodyString(text)
}
// SendJSON sends a JSON response
func SendJSON(ctx Ctx, 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 SendStatus(ctx Ctx, statusCode int) {
ctx.SetStatusCode(statusCode)
}
// SendError sends an error response with status code
func SendError(ctx Ctx, statusCode int, message string) {
ctx.SetStatusCode(statusCode)
ctx.SetContentType("text/plain; charset=utf-8")
ctx.SetBodyString(message)
}
// SendRedirect sends a redirect response
func SendRedirect(ctx Ctx, url string, statusCode ...int) {
code := fasthttp.StatusFound
if len(statusCode) > 0 {
code = statusCode[0]
}
ctx.Redirect(url, code)
}
// SendFile serves a file
func SendFile(ctx Ctx, filePath string) {
fasthttp.ServeFile(ctx, filePath)
}
// SendBytes sends raw bytes with optional content type
func SendBytes(ctx Ctx, data []byte, contentType ...string) {
if len(contentType) > 0 {
ctx.SetContentType(contentType[0])
}
ctx.SetBody(data)
}
// SendNoContent sends a 204 No Content response
func SendNoContent(ctx Ctx) {
ctx.SetStatusCode(fasthttp.StatusNoContent)
}