0
0
Fork 0

add database support

This commit is contained in:
Gibheer 2014-12-14 09:42:25 +01:00
parent e8fcff2cbb
commit c6cd31b2fd
4 changed files with 53 additions and 6 deletions

42
database.go Normal file
View File

@ -0,0 +1,42 @@
package main
import (
"database/sql"
_ "github.com/lib/pq"
)
type (
Post struct {
Title string
}
DBPosts []Post
)
var DB *sql.DB
func db_open(url string) error {
var err error
DB, err = sql.Open("postgres", url)
if err != nil {
return err
}
if _, err := DB.Exec("select 1"); err != nil {
return err
}
return nil
}
func GetPosts() DBPosts {
rows, err := DB.Query("select title from posts order by written desc")
if err != nil { return make(DBPosts, 0) }
result := make(DBPosts, 0)
for rows.Next() {
post := Post{}
rows.Scan(&post.Title)
result = append(result, post)
}
return result
}

View File

@ -48,6 +48,11 @@ func main() {
log.Printf("Error when loading the templates: %v", err)
os.Exit(1)
}
if err := db_open(config.Connection); err != nil {
log.Printf("Error when opening database connection: %v", err)
os.Exit(1)
}
defer DB.Close()
router := httprouter.New()
define_routes(router)

View File

@ -7,17 +7,17 @@ import (
// map URLs to their functions
func define_routes(router *httprouter.Router) {
router.HandlerFunc("GET", "/", Index)
router.HandlerFunc("GET", "/", RouteIndex)
router.GET("/post", Posts)
router.GET("/post", RoutePosts)
}
// the function for route /
func Index(w http.ResponseWriter, r *http.Request) {
func RouteIndex(w http.ResponseWriter, r *http.Request) {
Templates.ExecuteTemplate(w, "welcome", nil)
}
func Posts(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
posts := []int {0, 1, 2, 3, 4}
func RoutePosts(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
posts := GetPosts()
Templates.ExecuteTemplate(w, "posts/index", posts)
}

View File

@ -1,7 +1,7 @@
{{ template "header" . }}
<ul>
{{ range . }}
<li>{{ . }}
<li>{{ .Title }}
{{ end }}
</ul>
{{ template "footer" . }}