-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathhandler.go
52 lines (44 loc) · 1.17 KB
/
handler.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
package main
import (
"encoding/json"
"net/http"
"os"
)
func printHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
var req Request
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
setStatus(w, http.StatusBadRequest, "bad request")
return
}
err = req.Validate()
if err != nil {
setStatus(w, http.StatusBadRequest, err.Error())
return
}
err = PrintTag(req.Text, req.QrText)
if err != nil {
setStatus(w, http.StatusInternalServerError, err.Error())
return
}
setStatus(w, http.StatusOK, "tag printed")
}
func setStatus(w http.ResponseWriter, code int, msg string) error {
w.WriteHeader(code)
return json.NewEncoder(w).Encode(&Response{Status: msg})
}
// Function for implementing Basic Authentication
func HandleAuth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
reqUsername, reqPassword, ok := r.BasicAuth()
if !ok || reqUsername != os.Getenv("USERNAME") || reqPassword != os.Getenv("PASSWORD") {
setStatus(w, http.StatusUnauthorized, "Wrong Credentials")
return
}
next.ServeHTTP(w, r)
})
}