-
Notifications
You must be signed in to change notification settings - Fork 0
/
utilwebserver.go
56 lines (47 loc) · 1.05 KB
/
utilwebserver.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
package webmontag
import (
"database/sql"
"encoding/json"
"log"
"net/http"
"os"
"strings"
"github.com/joho/godotenv"
)
// setUp the db connection
func setUp() (*sql.DB, func()) {
godotenv.Load(".env")
dbURL := os.Getenv("DB_URL")
if dbURL == "" {
log.Fatal("DB_URL is empty")
}
conn, err := sql.Open("postgres", dbURL)
if err != nil {
log.Fatal("Can not connect to DB", err)
}
// Return connection and cleanup function
return conn, func() {
err := conn.Close()
if err != nil {
log.Fatal("Can not close DB", err)
}
}
}
// json responsewriter
func respondWithJSON(w http.ResponseWriter, code int, payload interface{}) {
dat, err := json.Marshal(payload)
if err != nil {
log.Printf("Failed to Marshal JSON %v \n", payload)
w.WriteHeader(500)
return
}
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(code)
w.Write(dat)
}
// secretkey checker
func keyCheck(r *http.Request) bool {
authorization := r.Header.Get("Authorization")
key := strings.TrimPrefix(authorization, "key ")
return key == Webserveroptions.Key
}