generated from PressureTank/genesis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
75 lines (63 loc) · 2.01 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package main
import (
"database/sql"
"net/http"
"github.com/gorilla/mux"
_ "github.com/mattn/go-sqlite3"
"go.uber.org/zap"
"github.com/PressureTank/AIOPass/backend/database/sqlite"
"github.com/PressureTank/AIOPass/backend/template"
"github.com/PressureTank/AIOPass/backend/user"
)
func main() {
// Initialize logger
logger, _ := zap.NewProduction()
defer logger.Sync() // Flushes buffer, if any
// Initialize SQLite database
db, err := sql.Open("sqlite3", "./database.db")
if err != nil {
logger.Error("Error opening database", zap.Error(err))
return
}
defer db.Close()
// Create tables if they do not exist
_, err = db.Exec(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
password TEXT NOT NULL
)
`)
if err != nil {
logger.Error("Error creating users table", zap.Error(err))
return
}
_, err = db.Exec(`
CREATE TABLE IF NOT EXISTS templates (
id INTEGER PRIMARY KEY AUTOINCREMENT,
prompt TEXT NOT NULL
`)
if err != nil {
logger.Error("Error creating templates table", zap.Error(err))
return
}
// Create instances of database, template, and user packages
dbInstance := sqlite.NewSQLiteDB(db)
templateHandler := template.NewTemplateHandler(dbInstance)
userHandler := user.NewUserHandler(dbInstance)
// Initialize HTTP router
r := mux.NewRouter()
// Register routes with handlers
r.HandleFunc("/register", userHandler.RegisterHandler).Methods("POST")
r.HandleFunc("/login", userHandler.LoginHandler).Methods("POST")
r.Handle("/templates", template.AuthMiddleware(templateHandler.GetTemplatesHandler)).Methods("GET")
r.Handle("/templates", template.AuthMiddleware(templateHandler.AddTemplateHandler)).Methods("POST")
r.Handle("/templates/{id}", template.AuthMiddleware(templateHandler.DeleteTemplateHandler)).Methods("DELETE")
// Start the server
port := ":8080"
logger.Info("Server started on port " + port)
err = http.ListenAndServe(port, r)
if err != nil {
logger.Error("Error starting server", zap.Error(err))
}
}