guestbook/cmd/web/main.go

104 lines
2.5 KiB
Go
Raw Permalink Normal View History

2024-10-16 04:34:57 +00:00
package main
import (
2024-11-11 19:55:01 +00:00
"crypto/tls"
2024-10-16 04:34:57 +00:00
"database/sql"
"flag"
"log/slog"
"net/http"
"os"
"text/template"
"time"
2024-10-16 04:34:57 +00:00
"git.32bit.cafe/32bitcafe/guestbook/internal/models"
"github.com/alexedwards/scs/sqlite3store"
"github.com/alexedwards/scs/v2"
2024-11-11 19:55:01 +00:00
"github.com/gorilla/schema"
_ "github.com/mattn/go-sqlite3"
2024-10-16 04:34:57 +00:00
)
type application struct {
2024-11-11 19:55:01 +00:00
sequence uint16
2024-10-16 04:34:57 +00:00
logger *slog.Logger
templateCache map[string]*template.Template
guestbooks *models.GuestbookModel
users *models.UserModel
guestbookComments *models.GuestbookCommentModel
sessionManager *scs.SessionManager
2024-11-11 19:55:01 +00:00
formDecoder *schema.Decoder
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()
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)
}
sessionManager := scs.New()
sessionManager.Store = sqlite3store.New(db)
sessionManager.Lifetime = 12 * time.Hour
2024-11-11 19:55:01 +00:00
formDecoder := schema.NewDecoder()
formDecoder.IgnoreUnknownKeys(true)
2024-10-16 04:34:57 +00:00
app := &application{
2024-11-11 19:55:01 +00:00
sequence: 0,
2024-10-16 04:34:57 +00:00
templateCache: templateCache,
logger: logger,
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-11-11 19:55:01 +00:00
formDecoder: formDecoder,
}
tlsConfig := &tls.Config{
CurvePreferences: []tls.CurveID{tls.X25519, tls.CurveP256},
}
srv := &http.Server {
Addr: *addr,
Handler: app.routes(),
ErrorLog: slog.NewLogLogger(logger.Handler(), slog.LevelError),
TLSConfig: tlsConfig,
IdleTimeout: time.Minute,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
2024-10-16 04:34:57 +00:00
}
logger.Info("Starting server", slog.Any("addr", *addr))
2024-10-16 04:34:57 +00:00
2024-11-11 19:55:01 +00:00
err = srv.ListenAndServeTLS("./tls/cert.pem", "./tls/key.pem")
2024-10-16 04:34:57 +00:00
logger.Error(err.Error())
os.Exit(1)
}
func openDB(dsn string) (*sql.DB, error) {
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-11-11 19:55:01 +00:00
func getUserId() int64 {
return 1
}