gorillamux

package
v0.95.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 30, 2022 License: MIT Imports: 7 Imported by: 186

Documentation

Overview

Package gorillamux implements a router.

It differs from the legacy router: * it provides somewhat granular errors: "path not found", "method not allowed". * it handles matching routes with extensions (e.g. /books/{id}.json) * it handles path patterns with a different syntax (e.g. /params/{x}/{y}/{z:.*})

Example
package main

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 main() {
	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 the schema: Field must be set to string or not be present
Schema:
  {
    "type": "string"
  }

Value:
  "object"

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewRouter

func NewRouter(doc *openapi3.T) (routers.Router, error)

NewRouter creates a gorilla/mux router. Assumes spec is .Validate()d TODO: Handle/HandlerFunc + ServeHTTP (When there is a match, the route variables can be retrieved calling mux.Vars(request))

Types

type Router

type Router struct {
	// contains filtered or unexported fields
}

Router helps link http.Request.s and an OpenAPIv3 spec

func (*Router) FindRoute

func (r *Router) FindRoute(req *http.Request) (*routers.Route, map[string]string, error)

FindRoute extracts the route and parameters of an http.Request

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL