This repository has been archived by the owner on Oct 24, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.go
70 lines (58 loc) · 1.43 KB
/
router.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
package handler
import (
"encoding/json"
"fmt"
"github.com/foae/dimago/clients/cacoo"
"github.com/foae/dimago/clients/github"
"github.com/go-chi/chi"
"log"
"net/http"
)
type Config struct {
GithubClient github.Communicator
CacooClient cacoo.Communicator
}
type Handler struct {
githubClient github.Communicator
cacooClient cacoo.Communicator
}
func NewHandler(cfg Config) http.Handler {
h := &Handler{
githubClient: cfg.GithubClient,
cacooClient: cfg.CacooClient,
}
r := chi.NewRouter()
r.Get("/", h.welcome)
r.Post("/", h.fetchProject)
return r
}
func (h *Handler) welcome(w http.ResponseWriter, r *http.Request) {
m := struct {
Message string `json:"message"`
Status int `json:"status"`
}{
Message: `OK`,
Status: http.StatusOK,
}
rsp, err := json.Marshal(m)
if err != nil {
log.Printf("handler: %v", err)
w.WriteHeader(http.StatusInternalServerError)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(m.Status)
_, _ = fmt.Fprintf(w, "%s", rsp)
}
func (h *Handler) fetchProject(w http.ResponseWriter, r *http.Request) {
var body struct{ URL string `json:"url"` }
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
if err := h.githubClient.RetrieveProject(body.URL); err != nil {
log.Printf("could not fetch project: %v", err)
w.WriteHeader(http.StatusBadRequest)
return
}
_, _ = fmt.Fprintf(w, `OK`)
}