-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
92 lines (77 loc) · 2.03 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package main
import (
"database/sql"
"flag"
"fmt"
_ "github.com/lib/pq"
"log"
"net/http"
"os"
)
var (
config configuration
db *sql.DB
env environment
imageInsertStmt *sql.Stmt
getImagePathStmt *sql.Stmt
searchImageByTitleStmt *sql.Stmt
getImageByHashStmt *sql.Stmt
recentImageStmt *sql.Stmt
)
func main() {
env0 := flag.String("env", "dev", "possible values: dev, prod, test")
configPath := flag.String("config", "config/config.json", "path of the confile file")
port := flag.String("port", ":8080", "port to run on")
logfile := flag.String("log", "", "path to the logfile; if left empty the app will log to stdout")
flag.Parse()
setLogOutput(*logfile)
env = environment(*env0)
config = loadConfiguration(*configPath)
initDb()
createPreparedStmts()
createSessionStore()
log.Printf("Started on %s port in %s mode", *port, env)
log.Fatal(http.ListenAndServe(*port, registerRoutes()))
}
func initDb() {
var err error
db, err = sql.Open("postgres", fmt.Sprintf("dbname=%s port=%d user=%s password=%s", config.Db.Name, config.Db.Port, config.Db.User, config.Db.Pass))
db.SetMaxIdleConns(config.Db.Pool)
db.SetMaxOpenConns(config.Db.Pool)
if err != nil {
log.Fatal(err)
}
}
func createPreparedStmts() {
var err error
imageInsertStmt, err = db.Prepare(ImageInsertSql)
if err != nil {
log.Fatal(err)
}
getImagePathStmt, err = db.Prepare(ImageGetPathSql)
if err != nil {
log.Fatal(err)
}
searchImageByTitleStmt, err = db.Prepare(SearchImageByTitleSql)
if err != nil {
log.Fatal(err)
}
getImageByHashStmt, err = db.Prepare(ImageByHashSql)
if err != nil {
log.Fatal(err)
}
recentImageStmt, err = db.Prepare(RecentImageSql)
if err != nil {
log.Fatal(err)
}
}
func setLogOutput(logfile string) {
if logfile != "" {
file, err := os.OpenFile(logfile, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
panic("cannot open file for logging")
}
log.SetOutput(file)
}
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
}