/
routes-utils.go
77 lines (65 loc) · 1.73 KB
/
routes-utils.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
package utils
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"github.com/gin-gonic/gin"
)
type K8sWorkloadResult struct {
Result interface{} `json:"result,omitempty"`
Error interface{} `json:"error,omitempty"`
}
func PrintPrettyPost(c *gin.Context) {
var out bytes.Buffer
body, _ := io.ReadAll(c.Request.Body)
err := json.Indent(&out, []byte(body), "", " ")
if err != nil {
fmt.Println(err)
}
fmt.Println(out.String())
}
func GetRequiredHeader(c *gin.Context, headerField string) string {
selectedField := c.Request.Header.Get(headerField)
if selectedField == "" {
c.JSON(http.StatusBadRequest, gin.H{
"err": fmt.Sprintf("Missing header '%s'.", headerField),
})
}
return selectedField
}
func NotFound(c *gin.Context, msg string) {
c.JSON(http.StatusNotFound, gin.H{
"err": msg,
})
}
func Unauthorized(c *gin.Context, msg string) {
c.JSON(http.StatusUnauthorized, gin.H{
"err": msg,
})
}
func MissingHeader(c *gin.Context, header string) {
c.JSON(http.StatusBadRequest, gin.H{
"err": fmt.Sprintf("Missing header '%s'.", header),
})
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("%s header is required", header))
}
func MissingQueryParameter(c *gin.Context, query string) {
c.JSON(http.StatusBadRequest, gin.H{
"err": fmt.Sprintf("Missing query parameter '%s'.", query),
})
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("%s query parameter is required", query))
}
func MalformedMessage(c *gin.Context, msg string) {
c.JSON(http.StatusBadRequest, gin.H{
"err": msg,
})
}
func HttpRespondForWorkloadResult(c *gin.Context, workloadResult K8sWorkloadResult) {
if workloadResult.Error == nil {
c.JSON(http.StatusOK, workloadResult)
} else {
c.JSON(http.StatusBadRequest, workloadResult)
}
}