/
base.go
78 lines (59 loc) · 2 KB
/
base.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
package handlers
import (
"context"
"encoding/json"
"fmt"
"net/http"
"github.com/kscout/serverless-registry-api/config"
"github.com/kscout/serverless-registry-api/metrics"
"github.com/Noah-Huppert/golog"
"github.com/google/go-github/v26/github"
"go.mongodb.org/mongo-driver/mongo"
)
// BaseHandler provides helper methods and commonly used variables for API endpoints to base
// their http.Handlers off
type BaseHandler struct {
// Ctx is the application context
Ctx context.Context
// Logger logs information
Logger golog.Logger
// Cfg is the application configuration
Cfg *config.Config
// Metrics holds Prometheus internal metrics recorders
Metrics metrics.Metrics
// MDb is a MongoDB database instance
MDb *mongo.Database
// MDbApps is the MongoDB apps collection instance
MDbApps *mongo.Collection
// Gh is the GitHub API client
Gh *github.Client
}
// GetChild makes a child instance of the base handler with a prefix
func (h BaseHandler) GetChild(prefix string) BaseHandler {
h.Logger.GetChild(prefix)
return h
}
// RespondJSON sends an object as a JSON encoded response
func (h BaseHandler) RespondJSON(w http.ResponseWriter, status int, resp interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
encoder := json.NewEncoder(w)
if err := encoder.Encode(resp); err != nil {
panic(fmt.Errorf("failed to encode response as JSON: %s", err.Error()))
}
}
// ParseJSON parses a request body as JSON
func (h BaseHandler) ParseJSON(r *http.Request, dest interface{}) {
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(dest); err != nil {
panic(fmt.Errorf("failed to decode request body as JSON: %s", err.Error()))
}
}
// RespondTEXT sends an object as a TEXT encoded response
func (h BaseHandler) RespondTEXT(w http.ResponseWriter, status int, resp string) {
w.Header().Set("Content-Type", "plain/text")
w.WriteHeader(status)
if _, err := fmt.Fprintf(w, resp); err != nil {
panic(fmt.Errorf("failed to write bash to body: %s", err.Error()))
}
}