1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
package handlers
import (
"net/http"
"fmt"
"text/template"
"github.com/gorilla/mux"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"wyo.town/netzah/models"
)
// CreateBlog displays the blog creation form
func CreateBlog(w http.ResponseWriter, r *http.Request) {
tmpl := template.Must(template.ParseFiles("templates/create_blog.html"))
tmpl.Execute(w, nil)
}
// StoreBlog handles the form submission for creating a blog
func StoreBlog(w http.ResponseWriter, r *http.Request) {
dsn := "host=localhost user=_postgresql password=postGRES dbname=netzah port=5432 sslmode=disable TimeZone=US/Mountain client_encoding=UTF8"
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
panic("failed to connect to database")
}
if r.Method == http.MethodPost {
var blog models.Blog
blog.Title = r.FormValue("title")
blog.Content = r.FormValue("content")
db.Create(&blog)
http.Redirect(w, r, "/blogs/"+fmt.Sprint(blog.ID), http.StatusSeeOther)
}
}
// GetBlog retrieves and displays a blog by ID
func GetBlog(w http.ResponseWriter, r *http.Request) {
dsn := "host=localhost user=_postgresql password=postGRES dbname=netzah port=5432 sslmode=disable TimeZone=US/Mountain client_encoding=UTF8"
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
panic("failed to connect to database")
}
id := mux.Vars(r)["id"]
var blog models.Blog
if err := db.First(&blog, id).Error; err != nil {
http.NotFound(w, r)
return
}
tmpl := template.Must(template.ParseFiles("templates/blog.html"))
tmpl.Execute(w, blog)
}
|