Skip to content

Commit 561b8c9

Browse files
authored
Merge pull request #1 from idbentley/feat/accept_header_multiplex
feat: introduce endpoint that multiplexes the response based on accept header.
2 parents 713c7ad + 629e70a commit 561b8c9

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-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.HandleFunc("/optional", acceptHeaders.HandleAcceptHeaderMultiplexing).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: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package acceptHeaders
2+
3+
import (
4+
"encoding/json"
5+
"net/http"
6+
"strings"
7+
8+
"github.com/speakeasy-api/speakeasy-api-test-service/internal/utils"
9+
)
10+
11+
func headersContains(headers []string, toCheck string) bool {
12+
for _, a := range headers {
13+
if strings.Contains(a, toCheck) {
14+
return true
15+
}
16+
}
17+
return false
18+
}
19+
20+
func HandleAcceptHeaderMultiplexing(w http.ResponseWriter, r *http.Request) {
21+
var obj interface{}
22+
if headersContains(r.Header["Accept"], "application/json") {
23+
err := json.Unmarshal([]byte("{\"type\":\"obj1\", \"value\": \"JSON\"}"), &obj)
24+
if err != nil {
25+
utils.HandleError(w, err)
26+
return
27+
}
28+
29+
w.Header().Set("Content-Type", "application/json; charset=utf-8")
30+
31+
if err := json.NewEncoder(w).Encode(obj); err != nil {
32+
utils.HandleError(w, err)
33+
}
34+
} else if headersContains(r.Header["Accept"], "text/plain") {
35+
36+
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
37+
w.Write([]byte("Success"))
38+
}
39+
40+
}

0 commit comments

Comments
 (0)