From d6fee8f5f9dad7ee97a962392a3c1d22cd4e452f Mon Sep 17 00:00:00 2001 From: Weetile Date: Thu, 13 Feb 2025 23:34:53 +0000 Subject: [PATCH] add json support --- main.go | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/main.go b/main.go index b491712..b15d043 100644 --- a/main.go +++ b/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)) } } -