From 2be19c9447344397fb863746c638a65ce296fb0a Mon Sep 17 00:00:00 2001 From: Sergey Gerasimov Date: Tue, 30 Jul 2013 15:06:56 +0300 Subject: [PATCH] Json support added --- core/api.go | 10 ++++++++++ example/app/controllers/books.go | 14 +++++++++++++- example/app/routes/books.go | 16 ++++++++-------- 3 files changed, 31 insertions(+), 9 deletions(-) diff --git a/core/api.go b/core/api.go index a883a01..b0a1520 100644 --- a/core/api.go +++ b/core/api.go @@ -4,6 +4,7 @@ import ( "strconv" "net/http" "github.com/grsmv/clio/helpers" + "encoding/json" ) // ------------------- utilities ------------------- @@ -48,6 +49,15 @@ func Delete (pattern string, handler func () string) { routes["DELETE"][pattern] = handler; } +// ------------------- json helper ------------------- + +func Json (obj interface{}) string { + SetHeader("Content-Type", "application/json") + + b, _ := json.Marshal(obj) + return string(b) +} + // ------------------- app runner ------------------- func Run (port int) { diff --git a/example/app/controllers/books.go b/example/app/controllers/books.go index 50e8a4a..b998d64 100644 --- a/example/app/controllers/books.go +++ b/example/app/controllers/books.go @@ -15,6 +15,11 @@ type Author struct { Works []Work } +type Message struct { + Name string + Body string +} + func Index () string { return Render("index") @@ -38,13 +43,20 @@ func Books () string { func Book () string { - SetHeader("Content-Type", "text/plain") + /* SetHeader("Content-Type", "text/plain") */ return "Book id #" + Splat()[0] + "
" + "url: " + Context().Request.URL.String() + "
" + "params: " + Params()["a"] } +func BookJ () string { + return Json ([]Message { + Message { "Alice", "Hello" }, + Message { "Alex", "Bye" }}) +} + + func BooksCreate () string { return "Create new book" } diff --git a/example/app/routes/books.go b/example/app/routes/books.go index 3ea9518..74505e0 100644 --- a/example/app/routes/books.go +++ b/example/app/routes/books.go @@ -6,12 +6,12 @@ import ( ) func BooksRoutes () { - // root - Get("/", controllers.Index) - Post ("/books", controllers.BooksCreate) - Get ("/books", controllers.Books) - Get ("/books/*", controllers.Book) - Put ("/books/*", controllers.BookUpdate) - Delete ("/books", controllers.BooksRemove) - Delete ("/books/*", controllers.BookRemove) + Get("/", controllers.Index) // root + Post ("/books", controllers.BooksCreate) + Get ("/books", controllers.Books) + Get ("/books/*", controllers.Book) + Get ("/books/*/json", controllers.BookJ) + Put ("/books/*", controllers.BookUpdate) + Delete ("/books", controllers.BooksRemove) + Delete ("/books/*", controllers.BookRemove) }