Skip to content

Instantly share code, notes, and snippets.

@calvinchengx
Last active December 14, 2015 03:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save calvinchengx/5024336 to your computer and use it in GitHub Desktop.
Save calvinchengx/5024336 to your computer and use it in GitHub Desktop.
package main
import (
"labix.org/v2/mgo"
"html/template"
"net/http"
"log"
"./signup"
)
var session *mgo.Session
var index = template.Must(template.ParseFiles(
"templates/_base.html",
"templates/index.html",
))
func Log(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("%s %s %s", r.RemoteAddr, r.Method, r.URL)
handler.ServeHTTP(w, r)
})
}
func hello(w http.ResponseWriter, req *http.Request) {
s := session.Clone()
defer s.Close()
// set up collection and query
coll := s.DB("golangproject").C("entries")
query := coll.Find(nil).Sort("-timestamp")
var entries []Entry
// execute the query
if err := query.All(&entries); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// execute the template
if err := index.Execute(w, entries); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func main() {
var err error
session, err = mgo.Dial("127.0.0.1")
if err != nil {
panic(err)
}
http.HandleFunc("/", hello)
http.HandleFunc("/sign", sign)
if err := http.ListenAndServe(":8080", Log(http.DefaultServeMux)); err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment