Skip to content

Instantly share code, notes, and snippets.

@jordic
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jordic/9230724131e3ba987ec6 to your computer and use it in GitHub Desktop.
Save jordic/9230724131e3ba987ec6 to your computer and use it in GitHub Desktop.
Specialized middlewares
package main
import (
"encoding/json"
"github.com/bmizerany/pat"
"html/template"
"log"
"net/http"
)
/*
https://gist.github.com/jordic/9230724131e3ba987ec6
Idea: Write some kind of "middlewares", especialized,
that cats as some "kind" of generic views...
I write, one JSONHandler... the only thing it does,
is transform to jason the output of the "Model" or "Collection"
But the same idea, could we done, with HtmlHandlers, that render
some tampletes... this way I think it would be easy, to write,
webapps ..
*/
const TPL = `
<h1>Hello {{.Obj.Name}} is this your surname {{.Obj.Surname}}?</h1>`
const TPLC = `
{{ range .Obj }}
<h1>Hello {{.Name}} is this your surname {{.Surname}} ?<h1>
{{ end }}
`
type JSONHandler func(http.ResponseWriter, *http.Request) interface{}
func (f JSONHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
out := f(w, r)
res, _ := json.Marshal(out)
w.Write(res)
}
type htmlHandler struct {
template string
name string
fu func(http.ResponseWriter, *http.Request) interface{}
}
func (h *htmlHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
out := h.fu(w, r)
t := template.Must(template.New(h.name).Parse(h.template))
res := map[string]interface{}{
"Obj": out,
}
t.Execute(w, res)
}
func HtmlHandler(f func(http.ResponseWriter, *http.Request) interface{},
template string, name string) http.Handler {
return &htmlHandler{template, name, f}
}
func main() {
m := pat.New()
m.Get("/hello/", JSONHandler(GetClient))
m.Get("/collection/", JSONHandler(GetClientCollection))
m.Get("/hello.html", HtmlHandler(GetClient, TPL, "object"))
m.Get("/collection.html", HtmlHandler(GetClientCollection, TPLC, "object2"))
http.Handle("/", m)
err := http.ListenAndServe(":9999", nil)
if err != nil {
log.Fatal("Listen and server", err)
}
}
func GetClient(w http.ResponseWriter, r *http.Request) interface{} {
return Name{Name: "John", Surname: "Smith"}
}
func GetClientCollection(w http.ResponseWriter, r *http.Request) interface{} {
var a = make([]Name, 2)
a[0] = Name{Name: "john", Surname: "Smith"}
a[1] = Name{Name: "Paul", Surname: "Denver"}
return a
}
type Name struct {
Name string
Surname string
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment