Skip to content

Commit 83ad29e

Browse files
committed
introduce endpoint that multiplexes the response based on accept header.
1 parent 713c7ad commit 83ad29e

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

cmd/server/main.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import (
1212
"github.com/gorilla/mux"
1313
"github.com/speakeasy-api/speakeasy-api-test-service/internal/auth"
1414
"github.com/speakeasy-api/speakeasy-api-test-service/internal/requestbody"
15+
"github.com/speakeasy-api/speakeasy-api-test-service/internal/acceptHeaders"
1516
)
1617

1718
func main() {
@@ -27,6 +28,7 @@ func main() {
2728
r.HandleFunc("/pagination/cursor", pagination.HandleCursor).Methods(http.MethodGet, http.MethodPut)
2829
r.HandleFunc("/retries", retries.HandleRetries).Methods(http.MethodGet)
2930
r.HandleFunc("/errors/{status_code}", errors.HandleErrors).Methods(http.MethodGet)
31+
r.HanldeFunc("/optional", acceptHeaders.AcceptHeaders).Methods(http.MethodGet)
3032

3133
log.Println("Listening on :8080")
3234
if err := http.ListenAndServe(":8080", r); err != nil {

internal/acceptHeaders/service.go

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package acceptHeaders
2+
3+
import (
4+
"encoding/json"
5+
"encoding/xml"
6+
"net/http"
7+
8+
"github.com/speakeasy-api/speakeasy-api-test-service/internal/utils"
9+
)
10+
11+
func HandleAcceptHeaderMultiplexing(w http.ResponseWriter, r *http.Request) {
12+
var obj interface{}
13+
if r.Header["Accept"] == "application/json" {
14+
err := json.Unmarshal([]byte("{\"Obj1\":\"obj1\"}"), &obj)
15+
if err != nil {
16+
utils.HandleError(w, err)
17+
return
18+
}
19+
20+
w.Header().Set("Content-Type", "application/json; charset=utf-8")
21+
22+
if err := json.NewEncoder(w).Encode(obj); err != nil {
23+
utils.HandleError(w, err)
24+
}
25+
} else if r.Header["Accept"] == "application/xml" {
26+
err := json.Unmarshal([]byte("{\"Obj2\":\"obj2\"}"), &obj)
27+
if err != nil {
28+
utils.HandleError(w, err)
29+
return
30+
}
31+
32+
w.Header().Set("Content-Type", "application/xml; charset=utf-8")
33+
34+
if err := xml.NewEncoder(w).Encode(obj); err != nil {
35+
utils.HandleError(w, err)
36+
}
37+
}
38+
39+
}

0 commit comments

Comments
 (0)