go-to-do/server.go
Martin Donnelly b21865118c init
2023-12-22 09:54:50 +00:00

121 lines
2.2 KiB
Go

/* https://blog.logrocket.com/building-simple-app-go-postgresql/ */
package main
import (
"database/sql"
"fmt"
"log"
"os"
_ "github.com/lib/pq"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/template/html/v2"
)
type todo struct {
Item string
}
func main() {
connStr := "postgresql://docker:docker@docker.lan:5432/todo?sslmode=disable"
db, err := sql.Open("postgres", connStr)
if err != nil {
log.Fatal(err)
}
engine := html.New("./views", ".html")
app := fiber.New(fiber.Config{
Views: engine,
})
app.Get("/", func(c *fiber.Ctx) error {
return indexHandler(c, db)
})
app.Post("/", func(c *fiber.Ctx) error {
return postHandler(c, db)
})
app.Put("/update", func(c *fiber.Ctx) error {
return putHandler(c, db)
})
app.Delete("/delete", func(c *fiber.Ctx) error {
return deleteHandler(c, db)
})
port := os.Getenv("PORT")
if port == "" {
port = "3000"
}
app.Static("/", "./public")
log.Fatalln(app.Listen(fmt.Sprintf(":%v", port)))
}
func indexHandler(c *fiber.Ctx, db *sql.DB) error {
var res string
var todos []string
rows, err := db.Query("SELECT * from todos")
defer rows.Close()
if err != nil {
log.Fatalln(err)
c.JSON("An error occured")
}
for rows.Next() {
rows.Scan(&res)
todos = append(todos, res)
}
return c.Render("index", fiber.Map{
"Todos": todos,
})
}
func postHandler(c *fiber.Ctx, db *sql.DB) error {
newTodo := todo{}
if err := c.BodyParser(&newTodo); err != nil {
log.Printf("An error occured: %v", err)
return c.SendString(err.Error())
}
fmt.Printf("%v", newTodo)
if newTodo.Item != "" {
_, err := db.Exec("INSERT into todos VALUES($1)", newTodo.Item)
if err != nil {
log.Fatalf("An error occured while executing query: %v", err)
}
}
return c.Redirect("/")
}
func putHandler(c *fiber.Ctx, db *sql.DB) error {
olditem := c.Query("olditem")
newitem := c.Query("newitem")
_, err := db.Exec("UPDATE todos SET item=$1 WHERE item=$2", newitem, olditem)
if err != nil {
log.Fatalf("An error occured while executing PUT query: %v", err)
}
return c.Redirect("/")
}
func deleteHandler(c *fiber.Ctx, db *sql.DB) error {
todoDelete := c.Query("item")
db.Exec("DELETE from todos WHERE item=$1", todoDelete)
return c.SendString("deleted")
}