-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
91 lines (70 loc) · 1.96 KB
/
main.go
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package main
import (
"fly-migrations/views"
"log"
"os"
"github.com/a-h/templ"
"github.com/gofiber/fiber/v2"
"github.com/jmoiron/sqlx"
"github.com/joho/godotenv"
_ "github.com/lib/pq"
)
func main() {
if err := godotenv.Load(); err != nil {
log.Print("No .env file found")
}
conn := createConnection()
app := fiber.New(fiber.Config{})
// app.Use(logger.New())
app.Static("/public", "./public")
app.Get("/", func(c *fiber.Ctx) error {
root := views.RootLayout("Skill Issue", GetJokes(conn))
return render(root, c)
})
app.Post("/create", func(c *fiber.Ctx) error {
var body jokeFormPayload
if err := c.BodyParser(&body); err != nil {
_form := views.JokeForm("", err.Error())
return render(_form, c)
}
if body.Joke == "" {
_form := views.JokeForm("", "Missing joke")
return render(_form, c)
}
if _, err := conn.Exec("insert into jokes (joke) values ($1)", body.Joke); err != nil {
log.Println("error creating joke", err)
_form := views.JokeForm(body.Joke, "Error creating joke")
return render(_form, c)
}
_form := views.JokeForm("", "")
_list := views.JokeList(GetJokes(conn))
c.Response().Header.SetContentType("text/html")
_form.Render(c.Context(), c.Response().BodyWriter())
_list.Render(c.Context(), c.Response().BodyWriter())
return nil
})
app.Listen(":8080")
}
type jokeFormPayload struct {
Joke string `form:"joke"`
}
func render(component templ.Component, c *fiber.Ctx) error {
c.Response().Header.SetContentType("text/html")
return component.Render(c.Context(), c.Response().BodyWriter())
}
func createConnection() *sqlx.DB {
db, err := sqlx.Connect("postgres", os.Getenv("DATABASE_URL"))
if err != nil {
log.Panicf("failed to open connection: %v\n", err)
}
return db
}
func GetJokes(conn *sqlx.DB) []string {
var jokes []string
err := conn.Select(&jokes, "select joke from jokes order by id desc")
if err != nil {
log.Println("error fetching jokes", err)
return []string{}
}
return jokes
}