add json support
All checks were successful
Build and Publish Multi-Architecture Image / build (push) Successful in 4m5s
All checks were successful
Build and Publish Multi-Architecture Image / build (push) Successful in 4m5s
This commit is contained in:
parent
bbdfb23f70
commit
d6fee8f5f9
13
main.go
13
main.go
@ -39,9 +39,16 @@ func randomFactHandler(facts []string, tmpl *template.Template) http.HandlerFunc
|
||||
index := rand.Intn(len(facts))
|
||||
fact := facts[index]
|
||||
|
||||
acceptHeader := r.Header.Get("Accept")
|
||||
userAgent := r.Header.Get("User-Agent")
|
||||
isCurl := strings.HasPrefix(strings.ToLower(userAgent), "curl")
|
||||
|
||||
if strings.Contains(strings.ToLower(acceptHeader), "application/json") {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
fmt.Fprintf(w, `{"fact": "%s"}`, escapeJSONString(fact))
|
||||
return
|
||||
}
|
||||
|
||||
if isCurl {
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
fmt.Fprintln(w, fact)
|
||||
@ -57,6 +64,11 @@ func randomFactHandler(facts []string, tmpl *template.Template) http.HandlerFunc
|
||||
}
|
||||
}
|
||||
|
||||
// escapeJSONString escapes double quotes in the JSON string.
|
||||
func escapeJSONString(input string) string {
|
||||
return strings.ReplaceAll(input, `"`, `\"`)
|
||||
}
|
||||
|
||||
func main() {
|
||||
facts, err := loadFacts()
|
||||
if err != nil {
|
||||
@ -75,4 +87,3 @@ func main() {
|
||||
panic(fmt.Sprintf("Server failed to start: %v", err))
|
||||
}
|
||||
}
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user