github.com/go-spatial/go-wfs@v0.1.4-0.20190401000911-c9fba2bb5188/wfs3/validation.go (about) 1 package wfs3 2 3 import ( 4 "fmt" 5 "io" 6 "net/http" 7 8 "github.com/getkin/kin-openapi/openapi3" 9 "github.com/getkin/kin-openapi/openapi3filter" 10 "github.com/xeipuuv/gojsonschema" 11 ) 12 13 // Validate a json response provided by a Reader using kin-openapi/openapi3 against the openapi3 14 // scaffolding set up in wfs3/openapi3.go 15 func ValidateJSONResponse(request *http.Request, path string, status int, header http.Header, respBodyRC io.ReadCloser) error { 16 var op *openapi3.Operation 17 switch request.Method { 18 case "GET": 19 if OpenAPI3Schema().Paths[path] == nil { 20 return fmt.Errorf("Path not found in schema: '%v'", path) 21 } 22 op = OpenAPI3Schema().Paths[path].Get 23 default: 24 return fmt.Errorf("unsupported request.Method: %v", request.Method) 25 } 26 27 rvi := openapi3filter.RequestValidationInput{ 28 Request: request, 29 Route: &openapi3filter.Route{ 30 Swagger: OpenAPI3Schema(), 31 Server: &openapi3.Server{}, 32 Path: path, 33 PathItem: &openapi3.PathItem{}, 34 Method: request.Method, 35 Operation: op, 36 }, 37 } 38 39 err := openapi3filter.ValidateResponse(nil, &openapi3filter.ResponseValidationInput{ 40 RequestValidationInput: &rvi, 41 Status: status, 42 Header: header, 43 Body: respBodyRC, 44 }) 45 return err 46 } 47 48 // Validate a Reader providing the response body against a string json schema 49 func ValidateJSONResponseAgainstJSONSchema(jsonResponse []byte, jsonSchema string) error { 50 schemaLoader := gojsonschema.NewStringLoader(jsonSchema) 51 respLoader := gojsonschema.NewStringLoader(string(jsonResponse)) 52 53 result, err := gojsonschema.Validate(schemaLoader, respLoader) 54 if err != nil { 55 return err 56 } 57 58 if !result.Valid() { 59 err = fmt.Errorf("document is invalid") 60 return err 61 } 62 63 return nil 64 }