Skip to content

Commit

Permalink
Json support added
Browse files Browse the repository at this point in the history
  • Loading branch information
Sergey Gerasimov committed Jul 30, 2013
1 parent 5795e2c commit 2be19c9
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 9 deletions.
10 changes: 10 additions & 0 deletions core/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"strconv"
"net/http"
"github.com/grsmv/clio/helpers"
"encoding/json"
)

// ------------------- utilities -------------------
Expand Down Expand Up @@ -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) {
Expand Down
14 changes: 13 additions & 1 deletion example/app/controllers/books.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ type Author struct {
Works []Work
}

type Message struct {
Name string
Body string
}


func Index () string {
return Render("index")
Expand All @@ -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] + "<br />" +
"url: " + Context().Request.URL.String() + "<br />" +
"params: " + Params()["a"]
}


func BookJ () string {
return Json ([]Message {
Message { "Alice", "Hello" },
Message { "Alex", "Bye" }})
}


func BooksCreate () string {
return "Create new book"
}
Expand Down
16 changes: 8 additions & 8 deletions example/app/routes/books.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

0 comments on commit 2be19c9

Please sign in to comment.