One of my favorite Go features is the ability to easily add handlers inside packages. This greatly simplifies the process of writing modular code.
Example:
File structure
|-- app.yaml |-- app | +-- http.go |-- templates | +-- base.html +-- github.com +-- storeski +-- appengine |-- products | |-- http.go | +-- templates | |-- list.html | +-- detail.html +-- account |-- http.go +-- templates |-- overview.html +-- notifications.html
Each package has an http.go file that uses the url prefix. For example, the products package under github.com/storeski/appengine/products should have any incoming URL starting with /products .
With this modular approach, it is useful to store templates in the products package. If you want to keep the basic template for the site, you can set an agreement in which you extend templates/base.html .
Example
Templates / base.html
<!DOCTYPE HTML> <html> <head> <title>{{.Store.Title}}</title> </head> <body> <div id="content"> {{template "content" .}} </div> </body> </html>
github.com/storeski/appengine/products/templates/list.html
{{define "content"}} <h1> Products List </h1> {{end}}
github.com/storeski/appengine/products/http.go
func init() { http.HandleFunc("/products", listHandler) } var listTmpl = template.Must(template.ParseFiles("templates/base.html", "github.com/storeski/appengine/products/templates/list.html")) func listHandler(w http.ResponseWriter, r *http.Request) { tc := make(map[string]interface{}) tc["Store"] = Store tc["Products"] = Products if err := listTmpl.Execute(w, tc); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } }
This approach is very interesting because it makes sharing applications / packages trivial. If I write a package that handles authentication, which takes responsibility for the /auth url. Any developer who then adds a package to their product root instantly has all the functionality. All they need to do is create a basic template ( templates/base.html ) and direct their users to /auth .
Kyle Finley Mar 06 '12 at 16:18 2012-03-06 16:18
source share