-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
61 lines (47 loc) · 1.75 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
package main
import (
"github.com/boltdb/bolt"
"github.com/gorilla/mux"
"github.com/verils/iwantoask/app"
"log"
"net/http"
"os"
"path"
"time"
)
const Version = "0.1.2"
func main() {
log.Printf("[INFO] iwantoask (iwantoask-%s) starting...", Version)
log.Printf("[INFO] iwantoask base path: '%s'", app.BasePath)
db := initDB()
defer db.Close()
handler := app.NewQuestionHandler(db)
router := mux.NewRouter()
router.HandleFunc(app.PrefixBasePath("/"), app.CookieAuth(handler.ListQuestions)).Methods(http.MethodGet)
router.HandleFunc(app.PrefixBasePath("/questions"), app.CookieAuth(handler.ListQuestions)).Methods(http.MethodGet)
router.HandleFunc(app.PrefixBasePath("/questions.json"), app.CookieAuth(handler.ListQuestionsJson)).Methods(http.MethodGet)
router.HandleFunc(app.PrefixBasePath("/ask"), app.CookieAuth(handler.AskQuestion)).Methods(http.MethodGet)
router.HandleFunc(app.PrefixBasePath("/ask"), app.CookieAuth(handler.SubmitQuestion)).Methods(http.MethodPost)
router.PathPrefix(app.PrefixBasePath("/")).Handler(http.StripPrefix(app.PrefixBasePath("/"), http.FileServer(http.Dir("static/"))))
log.Printf("[INFO] server started at port: %d", 8080)
_ = http.ListenAndServe(":8080", router)
}
func initDB() *bolt.DB {
dbPath := "data/iwantoask.db"
dbDir := path.Dir(dbPath)
if _, err := os.Stat(dbDir); os.IsNotExist(err) {
_ = os.Mkdir(dbDir, os.ModeDir)
}
db, err := bolt.Open(dbPath, 0600, &bolt.Options{Timeout: 1 * time.Second})
if err != nil {
log.Fatalf("[ERROR] failed to open database: %s", err.Error())
}
err = db.Update(func(tx *bolt.Tx) error {
_, e := tx.CreateBucketIfNotExists([]byte(app.BucketQuestions))
return e
})
if err != nil {
log.Fatalf("[ERROR] failed to create bucket: %s", err.Error())
}
return db
}