Skip to content

Commit bcecaee

Browse files
authored
update README.md with newer router/validator example (#554)
1 parent 142adad commit bcecaee

File tree

1 file changed

+18
-28
lines changed

1 file changed

+18
-28
lines changed

README.md

Lines changed: 18 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -65,23 +65,22 @@ route, pathParams, _ := router.FindRoute(httpRequest)
6565
package main
6666

6767
import (
68-
"bytes"
6968
"context"
70-
"encoding/json"
71-
"log"
69+
"fmt"
7270
"net/http"
7371

7472
"github.com/getkin/kin-openapi/openapi3"
7573
"github.com/getkin/kin-openapi/openapi3filter"
76-
legacyrouter "github.com/getkin/kin-openapi/routers/legacy"
74+
"github.com/getkin/kin-openapi/routers/gorillamux"
7775
)
7876

7977
func main() {
8078
ctx := context.Background()
81-
loader := openapi3.Loader{Context: ctx}
82-
doc, _ := loader.LoadFromFile("openapi3_spec.json")
83-
_ = doc.Validate(ctx)
84-
router, _ := legacyrouter.NewRouter(doc)
79+
loader := &openapi3.Loader{Context: ctx, IsExternalRefsAllowed: true}
80+
doc, _ := loader.LoadFromFile(".../My-OpenAPIv3-API.yml")
81+
// Validate document
82+
_ := doc.Validate(ctx)
83+
router, _ := gorillamux.NewRouter(doc)
8584
httpReq, _ := http.NewRequest(http.MethodGet, "/items", nil)
8685

8786
// Find route
@@ -93,31 +92,22 @@ func main() {
9392
PathParams: pathParams,
9493
Route: route,
9594
}
96-
if err := openapi3filter.ValidateRequest(ctx, requestValidationInput); err != nil {
97-
panic(err)
98-
}
95+
_ := openapi3filter.ValidateRequest(ctx, requestValidationInput)
9996

100-
var (
101-
respStatus = 200
102-
respContentType = "application/json"
103-
respBody = bytes.NewBufferString(`{}`)
104-
)
97+
// Handle that request
98+
// --> YOUR CODE GOES HERE <--
99+
responseHeaders := http.Header{"Content-Type": []string{"application/json"}}
100+
responseCode := 200
101+
responseBody := []byte(`{}`)
105102

106-
log.Println("Response:", respStatus)
103+
// Validate response
107104
responseValidationInput := &openapi3filter.ResponseValidationInput{
108105
RequestValidationInput: requestValidationInput,
109-
Status: respStatus,
110-
Header: http.Header{"Content-Type": []string{respContentType}},
111-
}
112-
if respBody != nil {
113-
data, _ := json.Marshal(respBody)
114-
responseValidationInput.SetBodyBytes(data)
115-
}
116-
117-
// Validate response.
118-
if err := openapi3filter.ValidateResponse(ctx, responseValidationInput); err != nil {
119-
panic(err)
106+
Status: responseCode,
107+
Header: responseHeaders,
120108
}
109+
responseValidationInput.SetBodyBytes(responseBody)
110+
_ := openapi3filter.ValidateResponse(ctx, responseValidationInput)
121111
}
122112
```
123113

0 commit comments

Comments
 (0)