udemy-go-web-1/cmd/web/main.go

96 lines
2.0 KiB
Go
Raw Normal View History

2024-06-26 15:30:39 +00:00
package main
import (
"encoding/gob"
2024-06-26 15:30:39 +00:00
"fmt"
2024-06-30 14:41:46 +00:00
"go-udemy-web-1/internal/config"
"go-udemy-web-1/internal/driver"
2024-06-30 14:41:46 +00:00
"go-udemy-web-1/internal/handlers"
"go-udemy-web-1/internal/helpers"
"go-udemy-web-1/internal/models"
2024-06-30 14:41:46 +00:00
"go-udemy-web-1/internal/render"
"log"
2024-06-26 15:30:39 +00:00
"net/http"
"os"
"time"
"github.com/alexedwards/scs/v2"
2024-06-26 15:30:39 +00:00
)
2024-06-26 15:41:50 +00:00
const portNumber = ":8080"
var (
app config.AppConfig
session *scs.SessionManager
infoLog *log.Logger
errorLog *log.Logger
)
2024-06-26 15:41:50 +00:00
// main is the main application function
2024-06-26 15:30:39 +00:00
func main() {
db, err := run()
if err != nil {
log.Fatal(err)
}
defer db.SQL.Close()
fmt.Printf("Starting application on port %s\n", portNumber)
srv := &http.Server{
Addr: portNumber,
Handler: routes(&app),
}
err = srv.ListenAndServe()
log.Fatal(err)
}
func run() (*driver.DB, error) {
// what am I going to put in the session
gob.Register(models.Reservation{})
2024-07-07 20:37:48 +00:00
gob.Register(models.User{})
gob.Register(models.Room{})
gob.Register(models.Restriction{})
// change this to true when in production
app.InProduction = false
session = scs.New()
session.Lifetime = 24 * time.Hour
session.Cookie.Persist = true
session.Cookie.SameSite = http.SameSiteLaxMode
session.Cookie.Secure = app.InProduction
app.Session = session
// connect to database
log.Println("Connecting to database...")
2024-07-08 21:16:13 +00:00
dsn := fmt.Sprintf("host=localhost port=5432 dbname=bookings user=%s password=%s", os.Getenv("PGUSER"), os.Getenv("PGPWD"))
db, err := driver.ConnectSQL(dsn)
if err != nil {
log.Fatal("Cannot connect to database! Dying...")
}
log.Println("Connected to database")
tc, err := render.CreateTemplateCache()
if err != nil {
2024-06-29 19:30:06 +00:00
log.Fatalf("cannot create template cache: %s", err)
return nil, err
}
app.TemplateCahce = tc
app.UseCache = false
infoLog = log.New(os.Stdout, "INFO\t", log.Ldate|log.Ltime)
app.InfoLog = infoLog
errorLog = log.New(os.Stdout, "ERROR\t", log.Ldate|log.Ltime|log.Lshortfile)
app.ErrorLog = errorLog
repo := handlers.NewRepo(&app, db)
handlers.NewHandlers(repo)
helpers.NewHelpers(&app)
2024-07-07 20:37:48 +00:00
render.NewRenderer(&app)
return db, nil
2024-06-26 15:30:39 +00:00
}