Skip to content

Commit

Permalink
exp/lighthorizon: *Correctly* set Content-Type, plus JSONify errors (
Browse files Browse the repository at this point in the history
  • Loading branch information
Shaptic authored Aug 5, 2022
1 parent 1c2072b commit c18e31f
Showing 1 changed file with 21 additions and 7 deletions.
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

0 comments on commit c18e31f

Please sign in to comment.