0
0
Fork 0

add route for a specific blog post

This commit is contained in:
Gibheer 2014-12-16 23:43:30 +01:00
parent c6cd31b2fd
commit e6a50c238c
2 changed files with 30 additions and 5 deletions

View File

@ -2,6 +2,7 @@ package main
import (
"database/sql"
"strconv"
_ "github.com/lib/pq"
)
@ -30,7 +31,22 @@ func db_open(url string) error {
func GetPosts() DBPosts {
rows, err := DB.Query("select title from posts order by written desc")
if err != nil { return make(DBPosts, 0) }
defer rows.Close()
return convertRowsToPosts(rows)
}
func GetPostsWithID(id_raw string) DBPosts {
id, err := strconv.Atoi(id_raw)
if err != nil { return make(DBPosts, 0) }
rows, err := DB.Query("select title from posts where id = $1", id)
if err != nil { return make(DBPosts, 0) }
defer rows.Close()
return convertRowsToPosts(rows)
}
func convertRowsToPosts(rows *sql.Rows) DBPosts {
result := make(DBPosts, 0)
for rows.Next() {
post := Post{}
@ -39,4 +55,3 @@ func GetPosts() DBPosts {
}
return result
}

View File

@ -1,19 +1,20 @@
package main
import (
"fmt"
"net/http"
"github.com/julienschmidt/httprouter"
)
// map URLs to their functions
func define_routes(router *httprouter.Router) {
router.HandlerFunc("GET", "/", RouteIndex)
func Routes(router *httprouter.Router) {
router.GET("/", RouteIndex)
router.GET("/post", RoutePosts)
router.GET("/post/:id", RoutePostsWithID)
}
// the function for route /
func RouteIndex(w http.ResponseWriter, r *http.Request) {
func RouteIndex(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
Templates.ExecuteTemplate(w, "welcome", nil)
}
@ -21,3 +22,12 @@ func RoutePosts(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
posts := GetPosts()
Templates.ExecuteTemplate(w, "posts/index", posts)
}
func RoutePostsWithID(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
posts := GetPostsWithID(ps.ByName("id"))
Templates.ExecuteTemplate(w, "posts/index", posts)
}
func NoOp(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
fmt.Fprintf(w, "Not implemented yet!")
}