hatecomputers.club/database/guestbook.go

51 lines
1.1 KiB
Go
Raw Normal View History

2024-03-29 18:35:04 -04:00
package database
import (
"database/sql"
"log"
"time"
_ "github.com/mattn/go-sqlite3"
)
type GuestbookEntry struct {
ID string `json:"id"`
Name string `json:"name"`
Message string `json:"message"`
CreatedAt time.Time `json:"created_at"`
}
func GetGuestbookEntries(db *sql.DB) ([]GuestbookEntry, error) {
log.Println("getting guest_book entries")
rows, err := db.Query("SELECT * FROM guest_book ORDER BY created_at DESC LIMIT 200")
if err != nil {
return nil, err
}
defer rows.Close()
var entries []GuestbookEntry
for rows.Next() {
var entry GuestbookEntry
err := rows.Scan(&entry.ID, &entry.Name, &entry.Message, &entry.CreatedAt)
if err != nil {
return nil, err
}
entries = append(entries, entry)
}
return entries, nil
}
func SaveGuestbookEntry(db *sql.DB, entry *GuestbookEntry) (*GuestbookEntry, error) {
log.Println("saving guest_book entry", entry.ID)
entry.CreatedAt = time.Now()
_, err := db.Exec("INSERT OR REPLACE INTO guest_book (id, name, message, created_at) VALUES (?, ?, ?, ?)", entry.ID, entry.Name, entry.Message, entry.CreatedAt)
if err != nil {
return nil, err
}
return entry, nil
}