2024-10-16 04:34:57 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
|
|
|
"flag"
|
|
|
|
"log/slog"
|
|
|
|
"net/http"
|
|
|
|
"os"
|
|
|
|
"text/template"
|
2024-10-23 05:25:30 +00:00
|
|
|
"time"
|
2024-10-16 04:34:57 +00:00
|
|
|
|
|
|
|
"git.32bit.cafe/32bitcafe/guestbook/internal/models"
|
2024-10-23 05:25:30 +00:00
|
|
|
"github.com/alexedwards/scs/sqlite3store"
|
|
|
|
"github.com/alexedwards/scs/v2"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
_ "github.com/mattn/go-sqlite3"
|
2024-10-16 04:34:57 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type application struct {
|
|
|
|
logger *slog.Logger
|
|
|
|
templateCache map[string]*template.Template
|
|
|
|
guestbooks *models.GuestbookModel
|
|
|
|
users *models.UserModel
|
|
|
|
guestbookComments *models.GuestbookCommentModel
|
2024-10-23 05:25:30 +00:00
|
|
|
sessionManager *scs.SessionManager
|
2024-10-16 04:34:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
addr := flag.String("addr", ":3000", "HTTP network address")
|
|
|
|
dsn := flag.String("dsn", "guestbook.db", "data source name")
|
|
|
|
flag.Parse()
|
|
|
|
|
2024-10-23 05:25:30 +00:00
|
|
|
logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug}))
|
2024-10-16 04:34:57 +00:00
|
|
|
|
|
|
|
db, err := openDB(*dsn)
|
|
|
|
if err != nil {
|
|
|
|
logger.Error(err.Error())
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
|
|
|
defer db.Close()
|
|
|
|
|
|
|
|
templateCache, err := newTemplateCache()
|
|
|
|
if err != nil {
|
|
|
|
logger.Error(err.Error())
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
|
|
|
|
2024-10-23 05:25:30 +00:00
|
|
|
sessionManager := scs.New()
|
|
|
|
sessionManager.Store = sqlite3store.New(db)
|
|
|
|
sessionManager.Lifetime = 12 * time.Hour
|
|
|
|
|
2024-10-16 04:34:57 +00:00
|
|
|
app := &application{
|
|
|
|
templateCache: templateCache,
|
|
|
|
logger: logger,
|
2024-10-23 05:25:30 +00:00
|
|
|
sessionManager: sessionManager,
|
2024-10-16 04:34:57 +00:00
|
|
|
guestbooks: &models.GuestbookModel{DB: db},
|
|
|
|
users: &models.UserModel{DB: db},
|
|
|
|
guestbookComments: &models.GuestbookCommentModel{DB: db},
|
|
|
|
}
|
|
|
|
|
2024-10-23 05:25:30 +00:00
|
|
|
logger.Info("Starting server", slog.Any("addr", *addr))
|
2024-10-16 04:34:57 +00:00
|
|
|
|
|
|
|
err = http.ListenAndServe(*addr, app.routes());
|
|
|
|
logger.Error(err.Error())
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
|
|
|
|
|
|
|
func openDB(dsn string) (*sql.DB, error) {
|
2024-10-23 05:25:30 +00:00
|
|
|
db, err := sql.Open("sqlite3", dsn)
|
2024-10-16 04:34:57 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if err = db.Ping(); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return db, nil
|
|
|
|
}
|
2024-10-23 05:25:30 +00:00
|
|
|
|
|
|
|
func getUserId() uuid.UUID {
|
|
|
|
userId, _ := decodeIdB64("laINnbnkTtyN5SYoCfSbXw")
|
|
|
|
return userId
|
|
|
|
}
|