forked from NXRSE/bank
-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathhttpApi.go
66 lines (55 loc) · 1.57 KB
/
httpApi.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
package main
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"github.com/ksred/bank/accounts"
"github.com/ksred/bank/appauth"
"github.com/ksred/bank/configuration"
"github.com/ksred/bank/payments"
)
func RunHttpServer() (err error) {
fmt.Println("HTTP Server called")
// Load app config
Config, err := configuration.LoadConfig()
if err != nil {
return errors.New("server.runServer: " + err.Error())
}
// Set config in packages
accounts.SetConfig(&Config)
payments.SetConfig(&Config)
appauth.SetConfig(&Config)
router := NewRouter()
//err = http.ListenAndServeTLS(":8443", "certs/server.pem", "certs/server.key", router)
err = http.ListenAndServeTLS(":8443", "certs/thebankoftoday.com.crt", "certs/thebankoftoday.com.key", router)
fmt.Println(err)
return
}
func Response(responseSuccess string, responseError error, w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
req := make(map[string]string)
// Check for error
if responseError != nil {
req["error"] = responseError.Error()
jsonResponse, err := json.Marshal(req)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("{error: 'Could not parse response'}"))
return
}
w.WriteHeader(http.StatusBadRequest)
w.Write(jsonResponse)
return
}
// Create response
req["response"] = string(responseSuccess)
jsonResponse, err := json.Marshal(req)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("{error: 'Could not parse response'}"))
return
}
w.WriteHeader(http.StatusOK)
w.Write(jsonResponse)
}