From cc11b626b6a98e554f131c4779ec2eb237eb01af Mon Sep 17 00:00:00 2001 From: Paul Brinkmeier Date: Thu, 18 Jul 2024 21:41:06 +0200 Subject: [PATCH] Use Accept header for returning JSON instead of plain text --- main.go | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/main.go b/main.go index a005775..54bc201 100644 --- a/main.go +++ b/main.go @@ -177,12 +177,19 @@ func main() { return } - for _, d := range departures.Departures { - fmt.Fprintf(w, "%2s %-11s %6s\n", - d.Symbol, - d.Direction[:min(11, len(d.Direction))], - d.Leaving, - ) + // Does not handle multiple media types + if r.Header.Get("Accept") == "application/json" { + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(departures) + } else { + // plain text + for _, d := range departures.Departures { + fmt.Fprintf(w, "%2s %-11s %6s\n", + d.Symbol, + d.Direction[:min(11, len(d.Direction))], + d.Leaving, + ) + } } }) log.Fatal(http.ListenAndServe(":8000", nil))