73 lines
1.7 KiB
Go
73 lines
1.7 KiB
Go
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)
|
|
}
|