From 3c239f611470a4aaa8e5c865999b4b4faf9a2fdf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pedro=20P=C3=A9rez?= Date: Tue, 12 Nov 2024 10:14:30 +0100 Subject: [PATCH] add json --- example/main.go | 5 +++++ ron.go | 10 ++++++++++ 2 files changed, 15 insertions(+) diff --git a/example/main.go b/example/main.go index 8bbb53a..1dc3df1 100644 --- a/example/main.go +++ b/example/main.go @@ -11,6 +11,7 @@ func main() { r := ron.New() r.GET("/", helloWorld) + r.GET("/json", helloWorldJSON) r.POST("/another", anotherHelloWorld) slog.Info("Server is running at http://localhost:8080") @@ -24,3 +25,7 @@ func helloWorld(c *ron.Context) { func anotherHelloWorld(c *ron.Context) { c.W.Write([]byte("another hello world")) } + +func helloWorldJSON(c *ron.Context) { + c.JSON(200, map[string]string{"message": "hello world"}) +} diff --git a/ron.go b/ron.go index df6909f..a779631 100644 --- a/ron.go +++ b/ron.go @@ -2,6 +2,7 @@ package ron import ( "context" + "encoding/json" "net/http" ) @@ -12,6 +13,15 @@ type Context struct { E *Engine } +func (c *Context) JSON(code int, data interface{}) { + c.W.WriteHeader(code) + c.W.Header().Set("Content-Type", "application/json") + encoder := json.NewEncoder(c.W) + if err := encoder.Encode(data); err != nil { + http.Error(c.W, err.Error(), http.StatusInternalServerError) + } +} + type Engine struct { mux *http.ServeMux }