add database support
This commit is contained in:
parent
e8fcff2cbb
commit
c6cd31b2fd
|
@ -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
|
||||
}
|
||||
|
5
main.go
5
main.go
|
@ -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)
|
||||
|
|
10
routes.go
10
routes.go
|
@ -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)
|
||||
}
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
{{ template "header" . }}
|
||||
<ul>
|
||||
{{ range . }}
|
||||
<li>{{ . }}
|
||||
<li>{{ .Title }}
|
||||
{{ end }}
|
||||
</ul>
|
||||
{{ template "footer" . }}
|
||||
|
|
Loading…
Reference in New Issue