File: example_test.go

package info (click to toggle)
golang-github-getkin-kin-openapi 0.124.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 4,288 kB
  • sloc: sh: 344; makefile: 4
file content (64 lines) | stat: -rw-r--r-- 1,582 bytes parent folder | download | duplicates (3)
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
package gorillamux_test

import (
	"context"
	"fmt"
	"net/http"

	"github.com/getkin/kin-openapi/openapi3"
	"github.com/getkin/kin-openapi/openapi3filter"
	"github.com/getkin/kin-openapi/routers/gorillamux"
)

func Example() {
	ctx := context.Background()
	loader := &openapi3.Loader{Context: ctx, IsExternalRefsAllowed: true}
	doc, err := loader.LoadFromFile("../../openapi3/testdata/pathref.openapi.yml")
	if err != nil {
		panic(err)
	}
	if err = doc.Validate(ctx); err != nil {
		panic(err)
	}
	router, err := gorillamux.NewRouter(doc)
	if err != nil {
		panic(err)
	}
	httpReq, err := http.NewRequest(http.MethodGet, "/test", nil)
	if err != nil {
		panic(err)
	}

	route, pathParams, err := router.FindRoute(httpReq)
	if err != nil {
		panic(err)
	}

	requestValidationInput := &openapi3filter.RequestValidationInput{
		Request:    httpReq,
		PathParams: pathParams,
		Route:      route,
	}
	if err := openapi3filter.ValidateRequest(ctx, requestValidationInput); err != nil {
		panic(err)
	}

	responseValidationInput := &openapi3filter.ResponseValidationInput{
		RequestValidationInput: requestValidationInput,
		Status:                 200,
		Header:                 http.Header{"Content-Type": []string{"application/json"}},
	}
	responseValidationInput.SetBodyBytes([]byte(`{}`))

	err = openapi3filter.ValidateResponse(ctx, responseValidationInput)
	fmt.Println(err)
	// Output:
	// response body doesn't match schema pathref.openapi.yml#/components/schemas/TestSchema: value must be a string
	// Schema:
	//   {
	//     "type": "string"
	//   }
	//
	// Value:
	//   {}
}