/
requestHandler.go
90 lines (72 loc) · 2.21 KB
/
requestHandler.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 api
import (
"encoding/json"
"fmt"
"net/http"
"os"
"github.com/RHEcosystemAppEng/SaaSi/deployer/deployer-lib/config"
"github.com/RHEcosystemAppEng/SaaSi/deployer/deployer-lib/deployer/app"
"github.com/RHEcosystemAppEng/SaaSi/deployer/deployer-lib/utils"
"github.com/gorilla/mux"
"github.com/sirupsen/logrus"
)
const (
APP_DEPLOYER_PATH = "/deploy/application"
HOST = "0.0.0.0"
POST = "POST"
GET = "GET"
CONTENT_TYPE = "application/json"
APPLICATION_NAME = "app-deployer"
STATUS = "up"
)
var (
err error
BuildVersion = "development"
router = mux.NewRouter()
)
type applicationInfo struct {
Name string `json:"name"`
Version string `json:"version"`
Status string `json:"status"`
}
func HandleRequests(args *config.Args, logger *logrus.Logger) {
logger.Infof("Running %s with version %s", os.Args[0], BuildVersion)
// define routes
router.Path(APP_DEPLOYER_PATH).HandlerFunc(deploy(args, logger)).Methods(POST)
router.Path(APP_DEPLOYER_PATH).HandlerFunc(info).Methods(GET)
// init hosting URL
url := fmt.Sprintf("%s:%d", HOST, args.Port)
logger.Infof("Starting listener as %s", url)
if err = http.ListenAndServe(url, router); err != nil {
logger.Fatal(err)
}
}
func handleResponse(rw http.ResponseWriter, logger *logrus.Logger, output *app.ApplicationOutput) {
if output.Status == utils.Failed.String() {
// set http parameters for error
logger.Error(output.ErrorMessage)
rw.WriteHeader(http.StatusBadRequest)
} else {
// set http parameters for ok
logger.Info("Process completed successfully")
rw.WriteHeader(http.StatusOK)
}
// marshal output to json format
jsonOutput, _ := json.Marshal(output)
// set http parameters and produce response
rw.Header().Set("Content-Type", CONTENT_TYPE)
rw.Write([]byte(jsonOutput))
}
func handleInfo(rw http.ResponseWriter) {
// set output parameters and marshal to json format
output := applicationInfo{
Name: APPLICATION_NAME,
Version: BuildVersion,
Status: STATUS,
}
jsonOutput, _ := json.Marshal(output)
// set http parameters and produce response
rw.WriteHeader(http.StatusOK)
rw.Header().Set("Content-Type", CONTENT_TYPE)
rw.Write([]byte(jsonOutput))
}