-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler_common.go
90 lines (77 loc) · 2.36 KB
/
handler_common.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
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"github.com/gorilla/sessions"
"github.com/thedevsaddam/renderer"
)
var sessionStore = sessions.NewCookieStore([]byte(os.Getenv("SESSION_KEY")))
type handlerCommon struct {
rnd *renderer.Render
}
const (
messageInvalidBoardID = "Invalid trello board id specified"
messageInvalidBoardList = "Invalid board or list specified"
messageSavedBoardList = "Linked board and list to etsy shop"
)
// Message is the message payload that would be send to client
type Message struct {
ErrorMessage string `json:"message"`
}
func newHandlerCommon() *handlerCommon {
h := &handlerCommon{}
opts := renderer.Options{
ParseGlobPattern: "./templates/*.html",
}
h.rnd = renderer.New(opts)
return h
}
func (hc *handlerCommon) ProcessErrorMessage(message string, w http.ResponseWriter, values ...interface{}) {
if len(values) > 0 {
message = fmt.Sprintf(message, values...)
}
payload, _ := json.Marshal(&Message{ErrorMessage: message})
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
w.Write(payload)
}
func (hc *handlerCommon) processAuthorizationError(message string,
w http.ResponseWriter, values ...interface{}) {
if len(values) > 0 {
message = fmt.Sprintf(message, values...)
}
payload, _ := json.Marshal(&Message{ErrorMessage: message})
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
w.Write(payload)
}
func (hc *handlerCommon) ProcessSuccessMessage(message string, w http.ResponseWriter) {
payload, _ := json.Marshal(&Message{ErrorMessage: message})
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(payload)
}
func (hc *handlerCommon) ProcessResponse(response interface{}, w http.ResponseWriter) {
payload, _ := json.Marshal(&response)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(payload)
}
func (hc *handlerCommon) GetUserIDFromSession(r *http.Request) int {
session, err := sessionStore.Get(r, "userSession")
if err != nil {
Error(err)
}
userID := session.Values["userID"].(int)
return userID
}
func (hc *handlerCommon) SaveUserIDInSession(r *http.Request, w http.ResponseWriter, userID int) {
session, err := sessionStore.Get(r, "userSession")
if err != nil {
Error(err)
}
session.Values["userID"] = userID
session.Save(r, w)
}