forked from Scalingo/sclng-backend-test-v1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandlers.go
79 lines (62 loc) · 1.69 KB
/
handlers.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
package main
import (
"encoding/json"
"github.com/sirupsen/logrus"
"net/http"
"strings"
)
type MyCustomHandler struct {
GithubAccessToken string
logger logrus.FieldLogger
}
func NewMyCustomHandler(logger logrus.FieldLogger, token string) *MyCustomHandler {
return &MyCustomHandler{
GithubAccessToken: token,
logger: logger,
}
}
func (h *MyCustomHandler) reposHandler(w http.ResponseWriter, r *http.Request, _ map[string]string) error {
//query params
language := r.URL.Query().Get("language")
license := r.URL.Query().Get("license")
repos, err := getRepos(h.GithubAccessToken)
if err != nil {
h.logger.WithError(err).Error("Failed to get public repositories")
}
t := NewTaskScheduler(h.GithubAccessToken, repos)
t.merge()
repos = h.filterByQueryParams(repos, language, license)
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
if err = json.NewEncoder(w).Encode(repos); err != nil {
h.logger.WithError(err).Error("Fail to encode JSON")
}
return nil
}
func (h *MyCustomHandler) filterByQueryParams(repos []map[string]any, language string, license string) []map[string]any {
var filteredRepos []map[string]any
for _, r := range repos {
found := false
repoLicense, ok := r["license"].(map[string]any)
if !ok {
continue
}
if strings.ToUpper(repoLicense["key"].(string)) == strings.ToUpper(license) {
found = true
}
repoLanguages, ok := r["languages"].(map[string]any)
if !ok {
continue
}
for l, _ := range repoLanguages {
if strings.ToUpper(l) == strings.ToUpper(language) {
found = true
break
}
}
if found {
filteredRepos = append(filteredRepos, r)
}
}
return filteredRepos
}