This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
package problem
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"github.com/itworx/pulse/internal/correlation"
|
||||
)
|
||||
|
||||
type Details struct {
|
||||
Type string `json:"type"`
|
||||
Title string `json:"title"`
|
||||
Status int `json:"status"`
|
||||
Code string `json:"code"`
|
||||
Detail string `json:"detail"`
|
||||
CorrelationID string `json:"correlationId"`
|
||||
Fields map[string]string `json:"fields,omitempty"`
|
||||
}
|
||||
|
||||
func Write(response http.ResponseWriter, request *http.Request, status int, code, title, detail string, fields map[string]string) {
|
||||
id := correlation.FromContext(request.Context())
|
||||
if id == "" {
|
||||
id = correlation.New()
|
||||
}
|
||||
details := Details{Type: "https://pulse.local/problems/" + code, Title: title, Status: status, Code: code, Detail: detail, CorrelationID: id, Fields: fields}
|
||||
response.Header().Set("Content-Type", "application/problem+json")
|
||||
response.Header().Set("Cache-Control", "private, no-store")
|
||||
response.Header().Set(correlation.Header, id)
|
||||
response.WriteHeader(status)
|
||||
_ = json.NewEncoder(response).Encode(details)
|
||||
}
|
||||
|
||||
func Middleware(next http.Handler) http.Handler {
|
||||
return correlation.Middleware(next)
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package problem
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/itworx/pulse/internal/correlation"
|
||||
)
|
||||
|
||||
func TestWriteProducesSafeProblemDetails(t *testing.T) {
|
||||
handler := correlation.Middleware(http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
|
||||
Write(response, request, http.StatusBadRequest, "INVALID_INPUT", "Invalid input", "The request could not be accepted.", nil)
|
||||
}))
|
||||
request := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
request.Header.Set(correlation.Header, "corr-1234")
|
||||
response := httptest.NewRecorder()
|
||||
handler.ServeHTTP(response, request)
|
||||
var details Details
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &details); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if details.Status != http.StatusBadRequest || details.CorrelationID != "corr-1234" || details.Code != "INVALID_INPUT" {
|
||||
t.Fatalf("unexpected problem: %#v", details)
|
||||
}
|
||||
if response.Header().Get("Cache-Control") != "private, no-store" {
|
||||
t.Fatalf("problem response cache control = %q", response.Header().Get("Cache-Control"))
|
||||
}
|
||||
if strings.Contains(response.Body.String(), "stack") || strings.Contains(response.Body.String(), "goroutine") {
|
||||
t.Fatal("problem response contains implementation details")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user