-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.go
145 lines (117 loc) · 3.83 KB
/
main.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
)
var scanningService ScanningService = ScanningService{}
// Google cloud run friendly listener string generator
func getListenerString() string {
host, hb := os.LookupEnv("HOST")
port, pb := os.LookupEnv("PORT")
if !pb {
port = "8000"
}
if !hb {
host = "0.0.0.0"
}
return fmt.Sprintf("%s:%s", host, port)
}
func initLogger() {
log.SetFormatter(&log.TextFormatter{})
log.SetOutput(os.Stderr)
// log.SetLevel(log.InfoLevel)
log.SetLevel(log.DebugLevel)
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello World!"))
}
func versionHandler(w http.ResponseWriter, r *http.Request) {
path, _ := filepath.Abs("./versions.json")
content, err := ioutil.ReadFile(path)
if err == nil {
w.Write(content)
} else {
w.Write([]byte("Failed to load versions.json"))
}
}
func default404Handler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("404 Not Found"))
}
func scanSubmissionHandler(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
scanRequest := ScanRequest{}
w.Header().Add("Content-Type", "application/json")
if err := decoder.Decode(&scanRequest); err != nil {
json.NewEncoder(w).Encode(map[string]string{"error": "Failed to decode request params"})
} else {
scanID := scanningService.AsyncScanImage(scanRequest)
json.NewEncoder(w).Encode(map[string]string{"scan_id": scanID})
}
}
func scanStatusHandler(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
w.Header().Add("Content-Type", "application/json")
status := scanningService.GetScanStatus(params["scan_id"])
if status == SCAN_STATUS_ERROR {
w.WriteHeader(http.StatusNotFound)
}
json.NewEncoder(w).Encode(map[string]string{"status": status})
}
func scanReportHandler(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
report, err := scanningService.GetScanReport(params["scan_id"])
w.Header().Add("Content-Type", "application/json")
if err != nil {
w.WriteHeader(http.StatusNotFound)
json.NewEncoder(w).Encode(map[string]string{"error": "Failed to get scan report"})
} else {
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(report)
}
}
func healthzHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
}
func corsMiddleware(r *mux.Router) mux.MiddlewareFunc {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "*")
next.ServeHTTP(w, req)
})
}
}
func corsOptionHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length")
w.WriteHeader(http.StatusNoContent)
}
func main() {
initLogger()
scanningService.Init()
r := mux.NewRouter()
r.HandleFunc("/", indexHandler)
r.HandleFunc("/healthz", healthzHandler)
r.HandleFunc("/version", versionHandler).Methods("GET")
r.HandleFunc("/scans/{scan_id}/status", scanStatusHandler).Methods("GET")
r.HandleFunc("/scans/{scan_id}", scanReportHandler).Methods("GET")
r.HandleFunc("/scans", scanSubmissionHandler).Methods("POST")
r.Methods("OPTIONS").HandlerFunc(corsOptionHandler)
r.Use(corsMiddleware(r))
loggingRouter := handlers.LoggingHandler(os.Stdout, r)
log.Infof("Starting HTTP server on %s", getListenerString())
err := http.ListenAndServe(getListenerString(), loggingRouter)
if err != nil {
log.Errorf("Failed to listen to local address, error; %#v", err)
}
}