-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.go
112 lines (94 loc) · 2.48 KB
/
app.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package swdocs
import (
"database/sql"
"fmt"
"sync"
log "github.com/sirupsen/logrus"
"net/http"
"os"
// We're using sqlite implementation of the sql interface.
_ "github.com/mattn/go-sqlite3"
"github.com/gorilla/mux"
)
// App is the struct representing our web application containing
// the database connection, the router, a mutex and its configuration.
type App struct {
Router *mux.Router
DB *sql.DB
Mutex sync.Mutex
Config AppConfig
}
// AppConfig holds the configuration used by the application.
type AppConfig struct {
Port string
TemplatesPath string
DbPath string
}
func (a *App) initializeRoutes() {
// Web Pages
a.Router.HandleFunc("/", a.homeHandler).Methods("GET")
a.Router.HandleFunc("/search", a.searchHandler).Methods("GET")
a.Router.HandleFunc("/{swDocName}", a.swDocHandler).Methods("GET")
// REST API
a.Router.HandleFunc("/api/v1/swdocs/", a.getSwDocsHandler).Methods("GET")
a.Router.HandleFunc("/api/v1/swdocs/{swDocName}", a.getSwDocHandler).Methods("GET")
a.Router.HandleFunc("/api/v1/swdocs/{swDocName}", a.deleteSwDocHandler).Methods("DELETE")
a.Router.HandleFunc("/api/v1/swdocs/apply", a.applySwDocHandler).Methods("POST")
}
func (a *App) createDbIfNotExists() (bool, error) {
_, err := os.Stat(a.Config.DbPath)
if err == nil {
log.Info("Database " + a.Config.DbPath + " already exists")
} else if os.IsNotExist(err) {
log.Info("Creating database " + a.Config.DbPath)
file, err := os.Create(a.Config.DbPath)
if err != nil {
return true, err
}
return false, file.Close()
}
return true, nil
}
func (a *App) populateDb() error {
_, err := a.DB.Exec("PRAGMA encoding = \"UTF-8\";")
if err != nil {
return err
}
statement, err := a.DB.Prepare(dbSchema)
if err != nil {
return err
}
_, err = statement.Exec()
if err != nil {
return err
}
return nil
}
// Initialize the web app database and routes.
func (a *App) Initialize() {
var err error
// Create DB file if not exists.
exists, err := a.createDbIfNotExists()
if err != nil {
log.Fatal(err.Error())
}
// Open up a DB connection.
a.DB, err = sql.Open("sqlite3", a.Config.DbPath)
if err != nil {
log.Fatal(err)
}
// Create tables in DB if it didn't exist before.
if !exists {
err = a.populateDb()
if err != nil {
log.Fatal(err)
}
}
// Initialize the web app routes.
a.Router = mux.NewRouter()
a.initializeRoutes()
}
// Run the web application.
func (a *App) Run() {
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", a.Config.Port), a.Router))
}