Skip to content

Commit

Permalink
feat: echo request headers in response over REST transport
Browse files Browse the repository at this point in the history
  • Loading branch information
vchudnov-g committed Apr 26, 2024
1 parent d3c515e commit 7a70b0a
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
2 changes: 2 additions & 0 deletions util/genrest/goviewcreator.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,8 @@ func NewView(model *gomodel.Model) (*goview.View, error) {
source.P(` backend.StdLog.Printf(" urlPathParams (expect %d, have %%d): %%q", numUrlPathParams, urlPathParams)`, len(allURLVariables))
source.P(` backend.StdLog.Printf(" urlRequestHeaders:\n%%s", resttools.PrettyPrintHeaders(r, " "))`)
source.P("")
source.P(" resttools.IncludeRequestHeadersInResponse(w, r)")
source.P("")
source.P(" if numUrlPathParams!=%d {", len(allURLVariables))
source.P(` backend.Error(w, http.StatusBadRequest, "found unexpected number of URL variables: expected %d, have %%d: %%#v", numUrlPathParams, urlPathParams)`, len(allURLVariables))
source.P(" return")
Expand Down
13 changes: 13 additions & 0 deletions util/genrest/resttools/headers.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,3 +98,16 @@ func PrettyPrintHeaders(request *http.Request, indentation string) string {
}
return strings.Join(lines, "\n")
}

// IncludeRequestHeadersInResponse includes all headers in the request `r` and includes them in the response `w`,
// prefixing each of these header keys with a constant to reflect they came from the request.
func IncludeRequestHeadersInResponse(w http.ResponseWriter, r *http.Request) {
const prefix = "x-showcase-request-"

responseHeaders := w.Header()
for requestKey, valueList := range r.Header {
for _, value := range valueList {
responseHeaders.Add(prefix+requestKey, value)
}
}
}

0 comments on commit 7a70b0a

Please sign in to comment.