From 8944c203940ead683f8fcaf4dd94a5539facdfd3 Mon Sep 17 00:00:00 2001 From: Sky Johnson Date: Fri, 15 Aug 2025 14:37:09 -0500 Subject: [PATCH] add send helpers --- send.go | 72 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 send.go diff --git a/send.go b/send.go new file mode 100644 index 0000000..5c08c2f --- /dev/null +++ b/send.go @@ -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) +}