-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp_response.go
67 lines (54 loc) · 1.69 KB
/
http_response.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package main
import (
"encoding/json"
"encoding/xml"
"fmt"
"net/http"
)
func buildResponseContentTypeHeader(rp RequestParams) string {
ctype := fmt.Sprintf("application/%s", string(rp.AcceptFormat))
if rp.AcceptVersion != FHIRVersionUnknown {
ctype = fmt.Sprintf("%s; fhirVersion=%s", ctype, rp.AcceptVersion.ShortVersion())
}
return ctype
}
func respondInKind(w http.ResponseWriter, r *http.Request, data any) {
var (
err error
log = getRequestLogger(r)
rp = getRequestParams(r)
)
log.Info("Processing response", "data", fmt.Sprintf("%T", data), "format", string(rp.AcceptFormat))
w.Header().Set("Content-Type", buildResponseContentTypeHeader(rp))
switch true {
case rp.AcceptFormat.IsJson():
je := json.NewEncoder(w)
if rp.Pretty {
je.SetIndent("", " ")
}
if err = je.Encode(data); err != nil {
log.Error("Error during JSON encode", "data", fmt.Sprintf("%T", data), "error", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
case rp.AcceptFormat.IsXml():
// write header
if _, err = w.Write([]byte(xml.Header)); err != nil {
log.Error("Error writing XML lead in", "err", err)
http.Error(w, "error writing XML lead in", http.StatusInternalServerError)
return
}
// init xml encoder
xe := xml.NewEncoder(w)
defer func() { _ = xe.Close() }()
if rp.Pretty {
xe.Indent("", " ")
}
if err = xe.Encode(data); err != nil {
log.Error("Error during XML encode", "data", fmt.Sprintf("%T", data), "error", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
default:
log.Error("Unknown format specified", "format", string(rp.AcceptFormat))
http.Error(w, "unknown format specified", http.StatusBadRequest)
}
}