-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimghandler.go
76 lines (61 loc) · 1.95 KB
/
imghandler.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
package shieldeddotdev
import (
"fmt"
"log/slog"
"net/http"
"github.com/ShieldedDotDev/shieldeddotdev/model"
"github.com/gorilla/mux"
"github.com/narqo/go-badge"
)
type ShieldHandler struct {
sm *model.ShieldMapper
}
func NewShieldHandler(sm *model.ShieldMapper) *ShieldHandler {
return &ShieldHandler{sm}
}
func (sh *ShieldHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
idst := vars["pid"]
s, err := sh.sm.GetFromPublicID(idst)
if err != nil {
slog.Info("error fetching shield from public id", slog.Any("error", err))
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
if s == nil {
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "image/svg+xml")
w.Header().Set("Cache-Control", "no-cache")
err = badge.Render(s.Title, s.Text, badge.Color("#"+s.Color), w)
if err != nil {
slog.Error("error rendering shield", slog.Any("error", err))
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
}
type StaticShieldHandler struct{}
func (ssh *StaticShieldHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
title := r.URL.Query().Get("title")
text := r.URL.Query().Get("text")
color := r.URL.Query().Get("color")
if color == "" {
color = "green"
}
normalizedColor, err := NormalizeColor(color)
if err != nil {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
seconds := 2592000
w.Header().Set("Content-Type", "image/svg+xml")
w.Header().Set("Pragma", "public")
w.Header().Set("Cache-Control", fmt.Sprintf("max-age=%d", seconds))
err = badge.Render(title, text, badge.Color("#"+normalizedColor), w)
if err != nil {
slog.Error("error rendering shield", slog.Any("error", err))
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
}