martini-contrib / render

Martini middleware/handler for easily rendering serialized JSON, XML, and HTML template responses.
MIT License
245 stars 57 forks source link

help: don't pass a function for every route #15

Closed jpcaruana closed 10 years ago

jpcaruana commented 10 years ago

Hi,

I am very new to golang, so maybe my question is a go issue. I'm sorry if it is the case.

Anyway, I would love not to be obliged to pass a func(r render.Render) to every route I create. It would be great to write something like this :

package main

import (
    "github.com/codegangsta/martini"
    "github.com/martini-contrib/render"
    "net/http"
)

func hello(params martini.Params, writer http.ResponseWriter, renderer *render.Render) string {
    return renderer.HTML(200, "mytemplate", nil)
}

func main() {
    m := martini.Classic()
    m.Use(render.Renderer())

    m.Get("/", hello)

    m.Run()
}

but I have the following error :

./server.go:10: renderer.HTML undefined (type *render.Render has no field or method HTML)

Is that possible ? I read something similar with the mgo package where the author created a mongo middleware : http://progadventure.blogspot.fr/2014/03/learning-go-with-martini-working-with.html

Thanks

unrolled commented 10 years ago

Sorry for the late reply, but better late than never :)

Your code works with a few minor tweaks. Mostly get rid of the return value in your hello function. The handler functions shouldn't return anything, and the render package takes care of writing out the response.

package main

import (
    "net/http"

    "github.com/go-martini/martini"
    "github.com/martini-contrib/render"
)

func hello(params martini.Params, writer http.ResponseWriter, renderer render.Render) {
    renderer.HTML(200, "mytemplate", nil)
}

func main() {
    m := martini.Classic()
    m.Use(render.Renderer())

    m.Get("/", hello)

    m.Run()
}
jpcaruana commented 10 years ago

ok thanks for your reply. I'll try this soon.