diff options
-rw-r--r-- | handler.go | 59 | ||||
-rw-r--r-- | router.go | 14 |
2 files changed, 41 insertions, 32 deletions
@@ -26,43 +26,40 @@ func static(filename string, staticRoot string) func(http.ResponseWriter, *http. } } -func index(db *Database, templateRoot string) func(http.ResponseWriter, *http.Request) { +func indexGet(w http.ResponseWriter, r *http.Request, db *Database, templateRoot string) { + + // get data from database + cmd := "SELECT id,title FROM recipes ORDER BY title;" + log.Printf("Query: %s", cmd) + rows, err := db.Backend.Query(cmd) + if err != nil { + Err(w, 1) + return + } + defer rows.Close() - return func(w http.ResponseWriter, r *http.Request) { + // prepare data store + type Element struct { + Id string + Title string + } + elements := make([]Element, 0) - // get data from database - cmd := "SELECT id,title FROM recipes ORDER BY title;" - log.Printf("Query: %s", cmd) - rows, err := db.Backend.Query(cmd) + // scan database rows to data store + for rows.Next() { + var element Element + err := rows.Scan(&element.Id, &element.Title) if err != nil { - Err(w, 1) + Err(w, 2) return + } else { + elements = append(elements, element) } - defer rows.Close() - - // prepare data store - type Element struct { - Id string - Title string - } - elements := make([]Element, 0) - - // scan database rows to data store - for rows.Next() { - var element Element - err := rows.Scan(&element.Id, &element.Title) - if err != nil { - Err(w, 2) - return - } else { - elements = append(elements, element) - } - } - - // render and return template - path := filepath.Join(templateRoot, "index.html") - ServeTemplate(w, "index", path, elements) } + + // render and return template + path := filepath.Join(templateRoot, "index.html") + ServeTemplate(w, "index", path, elements) } func recipe(db *Database, templateRoot string) func(http.ResponseWriter, *http.Request) { @@ -6,9 +6,21 @@ import ( "net/http" ) +func indexMux(db *Database, templateRoot string) func(http.ResponseWriter, *http.Request) { + + return func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case "GET": + indexGet(w, r, db, templateRoot) + default: + // TODO + } + } +} + func RunServer(config HttpConfig, db *Database) { - http.HandleFunc("/", index(db, config.Templates)) + http.HandleFunc("/", indexMux(db, config.Templates)) http.HandleFunc("/recipe", recipe(db, config.Templates)) |