Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

exp/lighthorizon: *Correctly* set Content-Type, plus JSONify errors #4513

Merged
merged 2 commits into from
Aug 5, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 21 additions & 7 deletions exp/lighthorizon/actions/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package actions
import (
"embed"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strconv"
Expand Down Expand Up @@ -55,22 +54,37 @@ type pagination struct {
}

func sendPageResponse(w http.ResponseWriter, page hal.Page) {
w.Header().Set("Content-Type", "application/hal+json; charset=utf-8")
encoder := json.NewEncoder(w)
encoder.SetIndent("", " ")
err := encoder.Encode(page)
if err != nil {
log.Error(err)
sendErrorResponse(w, http.StatusInternalServerError, "")
} else {
w.Header().Set("Content-Type", "application/hal+json; charset=utf-8")
}
}

func sendErrorResponse(w http.ResponseWriter, errorCode int, errorMsg string) {
if errorMsg != "" {
http.Error(w, fmt.Sprintf("Error: %s", errorMsg), errorCode)
} else {
http.Error(w, string(serverError), errorCode)
if errorMsg == "" {
errorMsg = string(serverError)
}

w.Header().Set("Content-Type", "application/json; charset=utf-8")

// TODO: Use Horizon's existing Problem
errBlob := struct {
Message string `json:"error"`
Status int `json:"status"`
}{
Message: errorMsg,
Status: errorCode,
}

encoder := json.NewEncoder(w)
encoder.SetIndent("", " ")
if err := encoder.Encode(errBlob); err != nil {
log.Error(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}

Expand Down