all repos — auth-boilerplate @ 1d2161533766f00180886b1c08838865e35013d3

A simple Go web-app boilerplate.

src/app/init.go (view raw)

 1package app
 2
 3import (
 4	"html/template"
 5	"log"
 6	"net/http"
 7	"os"
 8	"path/filepath"
 9	"time"
10
11	"github.com/birabittoh/auth-boilerplate/src/auth"
12	"github.com/birabittoh/auth-boilerplate/src/email"
13	"github.com/birabittoh/myks"
14	"github.com/glebarez/sqlite"
15	"github.com/joho/godotenv"
16	"gorm.io/gorm"
17)
18
19type key int
20
21type User struct {
22	gorm.Model
23	Username     string `gorm:"unique"`
24	Email        string `gorm:"unique"`
25	PasswordHash string
26	Salt         string
27}
28
29const (
30	dataDir = "data"
31	dbName  = "app.db"
32)
33
34var (
35	db *gorm.DB
36	g  *auth.Auth
37	m  *email.Client
38
39	baseUrl string
40	port    string
41
42	ks           = myks.New[uint](0)
43	durationDay  = 24 * time.Hour
44	durationWeek = 7 * durationDay
45	templates    = template.Must(template.ParseGlob("templates/*.html"))
46)
47
48const userContextKey key = 0
49
50func Main() {
51	err := godotenv.Load()
52	if err != nil {
53		log.Println("Error loading .env file")
54	}
55
56	port = os.Getenv("APP_PORT")
57	if port == "" {
58		port = "3000"
59	}
60
61	baseUrl = os.Getenv("APP_BASE_URL")
62	if baseUrl == "" {
63		baseUrl = "http://localhost:" + port
64	}
65
66	// Init auth and email
67	g = auth.NewAuth(os.Getenv("APP_PEPPER"))
68	m = loadEmailConfig()
69
70	os.MkdirAll(dataDir, os.ModePerm)
71	dbPath := filepath.Join(dataDir, dbName) + "?_pragma=foreign_keys(1)"
72	db, err = gorm.Open(sqlite.Open(dbPath), &gorm.Config{})
73	if err != nil {
74		log.Fatal(err)
75	}
76
77	db.AutoMigrate(&User{})
78
79	// Handle routes
80	http.HandleFunc("GET /", loginRequired(examplePage))
81	http.HandleFunc("GET /register", getRegisterHandler)
82	http.HandleFunc("GET /login", getLoginHandler)
83	http.HandleFunc("GET /reset-password", getResetPasswordHandler)
84	http.HandleFunc("GET /reset-password-confirm", getResetPasswordConfirmHandler)
85	http.HandleFunc("GET /logout", logoutHandler)
86
87	http.HandleFunc("POST /login", postLoginHandler)
88	http.HandleFunc("POST /register", postRegisterHandler)
89	http.HandleFunc("POST /reset-password", postResetPasswordHandler)
90	http.HandleFunc("POST /reset-password-confirm", postResetPasswordConfirmHandler)
91
92	// Start serving
93	log.Println("Port: " + port)
94	log.Println("Server started: " + baseUrl)
95	log.Fatal(http.ListenAndServe(":"+port, nil))
96}