Repository: deepmap/oapi-codegen
Pull request #771 (2022-10-03 08:50:38)

Ensure embedded spec contains all necessary OpenAPI documents
When using a schema that uses `$ref`s to an external file, although we
generate the mappings appropriately, this then leads to the embedded
spec being misaligned, as it continues to use the `$ref` to that
external file, which then is not available when calling i.e.
`GetSwagger`.

We can take advantage of the `InternalizeRefs` method to perform an
in-place modification to apply those external references into a single,
embeddable spec.



Patch:
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 46f53f7..e7a81a8 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -1,5 +1,5 @@
 name: Build project
-on: [ push, pull_request ]
+on: [push, pull_request]
 jobs:
   build:
     name: Build
diff --git a/.github/workflows/generate.yml b/.github/workflows/generate.yml
index e6d92b6..03e1b11 100644
--- a/.github/workflows/generate.yml
+++ b/.github/workflows/generate.yml
@@ -1,5 +1,5 @@
 name: Ensure generated files are up-to-date
-on: [ push, pull_request ]
+on: [push, pull_request]
 jobs:
   build:
     name: Build
diff --git a/.github/workflows/tidy.yml b/.github/workflows/tidy.yml
index 8863c54..de4cfc9 100644
--- a/.github/workflows/tidy.yml
+++ b/.github/workflows/tidy.yml
@@ -1,5 +1,5 @@
 name: Ensure `go mod tidy` has been run
-on: [ push, pull_request ]
+on: [push, pull_request]
 jobs:
   build:
     name: Build
diff --git a/README.md b/README.md
index ba45d6b..0510c8a 100644
--- a/README.md
+++ b/README.md
@@ -289,7 +289,7 @@ func (*PetStoreImpl) GetPets(ctx context.Context, request GetPetsRequestObject)
 ```
 For a complete example see `/examples/petstore-expanded/strict`.
 
-Code is generated with a configuration flag `generate: strict-server: true` along with any other server (echo, chi, gin and gorilla are supported).
+Code is generation with a configuration flag `genrate: strict-server: true` along with any other server (echo, chi, gin and gorilla are supported).
 The generated strict wrapper can then be used as an implementation for `ServerInterface`. Setup example:
 ```go
 func SetupHandler() {
diff --git a/cmd/oapi-codegen/oapi-codegen.go b/cmd/oapi-codegen/oapi-codegen.go
index 0065f6a..a3833e7 100644
--- a/cmd/oapi-codegen/oapi-codegen.go
+++ b/cmd/oapi-codegen/oapi-codegen.go
@@ -21,9 +21,10 @@ import (
 	"runtime/debug"
 	"strings"
 
+	"gopkg.in/yaml.v2"
+
 	"github.com/deepmap/oapi-codegen/pkg/codegen"
 	"github.com/deepmap/oapi-codegen/pkg/util"
-	"gopkg.in/yaml.v2"
 )
 
 func errExit(format string, args ...interface{}) {
@@ -38,7 +39,6 @@ var (
 	flagOutputConfig   bool
 	flagPrintVersion   bool
 	flagPackageName    string
-	flagPrintUsage     bool
 
 	// The options below are deprecated, and they will be removed in a future
 	// release. Please use the new config file format.
@@ -60,7 +60,7 @@ type configuration struct {
 }
 
 // oldConfiguration is deprecated. Please add no more flags here. It is here
-// for backwards compatibility, and it will be removed in the future.
+// for backwards compatibility and it will be removed in the future.
 type oldConfiguration struct {
 	PackageName        string                       `yaml:"package"`
 	GenerateTargets    []string                     `yaml:"generate"`
@@ -81,8 +81,6 @@ func main() {
 	flag.StringVar(&flagConfigFile, "config", "", "a YAML config file that controls oapi-codegen behavior")
 	flag.BoolVar(&flagPrintVersion, "version", false, "when specified, print version and exit")
 	flag.StringVar(&flagPackageName, "package", "", "The package name for generated code")
-	flag.BoolVar(&flagPrintUsage, "help", false, "show this help and exit")
-	flag.BoolVar(&flagPrintUsage, "h", false, "same as -help")
 
 	// All flags below are deprecated, and will be removed in a future release. Please do not
 	// update their behavior.
@@ -98,11 +96,6 @@ func main() {
 
 	flag.Parse()
 
-	if flagPrintUsage {
-		flag.Usage()
-		os.Exit(0)
-	}
-
 	if flagPrintVersion {
 		bi, ok := debug.ReadBuildInfo()
 		if !ok {
@@ -115,9 +108,8 @@ func main() {
 	}
 
 	if flag.NArg() < 1 {
-		errExit("Please specify a path to a OpenAPI 3.0 spec file\n")
-	} else if flag.NArg() > 1 {
-		errExit("Only one OpenAPI 3.0 spec file is accepted and it must be the last CLI argument\n")
+		fmt.Println("Please specify a path to a OpenAPI 3.0 spec file")
+		os.Exit(1)
 	}
 
 	// We will try to infer whether the user has an old-style config, or a new
diff --git a/examples/authenticated-api/api.yaml b/examples/authenticated-api/api.yaml
index a0243f9..73b00b9 100644
--- a/examples/authenticated-api/api.yaml
+++ b/examples/authenticated-api/api.yaml
@@ -27,7 +27,7 @@ paths:
         write.
       security:
         - BearerAuth:
-            - "things:w"
+          - "things:w"
       requestBody:
         description: A thing to insert. Returns the inserted thing with an ID
         required: true
diff --git a/examples/authenticated-api/echo/server/jwt_authenticator.go b/examples/authenticated-api/echo/server/jwt_authenticator.go
index 4d6b334..55e0f72 100644
--- a/examples/authenticated-api/echo/server/jwt_authenticator.go
+++ b/examples/authenticated-api/echo/server/jwt_authenticator.go
@@ -17,11 +17,9 @@ type JWSValidator interface {
 	ValidateJWS(jws string) (jwt.Token, error)
 }
 
-var (
-	ErrNoAuthHeader      = errors.New("Authorization header is missing")
-	ErrInvalidAuthHeader = errors.New("Authorization header is malformed")
-	ErrClaimsInvalid     = errors.New("Provided claims do not match expected scopes")
-)
+var ErrNoAuthHeader = errors.New("Authorization header is missing")
+var ErrInvalidAuthHeader = errors.New("Authorization header is malformed")
+var ErrClaimsInvalid = errors.New("Provided claims do not match expected scopes")
 
 // GetJWSFromRequest extracts a JWS string from an Authorization: Bearer <jws> header
 func GetJWSFromRequest(req *http.Request) (string, error) {
diff --git a/examples/authenticated-api/echo/server/server.go b/examples/authenticated-api/echo/server/server.go
index 9c18c43..c57a897 100644
--- a/examples/authenticated-api/echo/server/server.go
+++ b/examples/authenticated-api/echo/server/server.go
@@ -6,10 +6,11 @@ import (
 	"sort"
 	"sync"
 
-	"github.com/deepmap/oapi-codegen/examples/authenticated-api/echo/api"
-	"github.com/deepmap/oapi-codegen/pkg/middleware"
 	"github.com/getkin/kin-openapi/openapi3filter"
 	"github.com/labstack/echo/v4"
+
+	"github.com/deepmap/oapi-codegen/examples/authenticated-api/echo/api"
+	"github.com/deepmap/oapi-codegen/pkg/middleware"
 )
 
 type server struct {
diff --git a/examples/petstore-expanded/chi/api/cfg.yaml b/examples/petstore-expanded/chi/api/cfg.yaml
index d1a29f3..6d2fa08 100644
--- a/examples/petstore-expanded/chi/api/cfg.yaml
+++ b/examples/petstore-expanded/chi/api/cfg.yaml
@@ -3,6 +3,4 @@ generate:
   chi-server: true
   models: true
   embedded-spec: true
-compatibility:
-  apply-chi-middleware-first-to-last: true
 output: petstore.gen.go
diff --git a/examples/petstore-expanded/chi/api/petstore.gen.go b/examples/petstore-expanded/chi/api/petstore.gen.go
index 59e517c..4234451 100644
--- a/examples/petstore-expanded/chi/api/petstore.gen.go
+++ b/examples/petstore-expanded/chi/api/petstore.gen.go
@@ -114,8 +114,8 @@ func (siw *ServerInterfaceWrapper) FindPets(w http.ResponseWriter, r *http.Reque
 		siw.Handler.FindPets(w, r, params)
 	})
 
-	for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- {
-		handler = siw.HandlerMiddlewares[i](handler)
+	for _, middleware := range siw.HandlerMiddlewares {
+		handler = middleware(handler)
 	}
 
 	handler.ServeHTTP(w, r.WithContext(ctx))
@@ -129,8 +129,8 @@ func (siw *ServerInterfaceWrapper) AddPet(w http.ResponseWriter, r *http.Request
 		siw.Handler.AddPet(w, r)
 	})
 
-	for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- {
-		handler = siw.HandlerMiddlewares[i](handler)
+	for _, middleware := range siw.HandlerMiddlewares {
+		handler = middleware(handler)
 	}
 
 	handler.ServeHTTP(w, r.WithContext(ctx))
@@ -155,8 +155,8 @@ func (siw *ServerInterfaceWrapper) DeletePet(w http.ResponseWriter, r *http.Requ
 		siw.Handler.DeletePet(w, r, id)
 	})
 
-	for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- {
-		handler = siw.HandlerMiddlewares[i](handler)
+	for _, middleware := range siw.HandlerMiddlewares {
+		handler = middleware(handler)
 	}
 
 	handler.ServeHTTP(w, r.WithContext(ctx))
@@ -181,8 +181,8 @@ func (siw *ServerInterfaceWrapper) FindPetByID(w http.ResponseWriter, r *http.Re
 		siw.Handler.FindPetByID(w, r, id)
 	})
 
-	for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- {
-		handler = siw.HandlerMiddlewares[i](handler)
+	for _, middleware := range siw.HandlerMiddlewares {
+		handler = middleware(handler)
 	}
 
 	handler.ServeHTTP(w, r.WithContext(ctx))
@@ -325,29 +325,29 @@ var swaggerSpec = []string{
 	"od7rzDImj2LmhoO8fWM6I9uR2l9aUTK7znjKGVfffND+9iE0S+KwMrtdZxI9Fk40mPkvZtpwv/x+15mP",
 	"9HRHcok7oL+y3Uf0BHEJsiYYSS437Izg6jLup+34etwLoHV3hTdhQ+c+Lc38l2fz/4mWZm7+b3YUYjap",
 	"MJty2XUvk+HhEtLPgR8LAQ/nuE7F+MN3V8R4gZQHc7+73+llDsvYJA+CtuImj+zM3ODIQuj/mJ9wtaLU",
-	"czTdRLH53K7Bu7sF/EToTWdK0qC1yJjns9lJ0K57kcU7yOhHRzVa1ihQMmVAzSZLTASYAQPQ17ZMIgzk",
-	"Y8iSUAiWhFISZeBQOfg0UtAnve1vII9keckW61adcWwpZDqaw7wb0a4J3vQ3F5ifnp56rLf7mFazKTbP",
-	"/rR4/+Hj5w+/e9Pf9GvxrjqGks+flp8pbdjS1cRndc1M5WBxp6zdTXmazmwo5cbK7/ub/kYfHUcKOLKZ",
-	"m7f1UmdGlHX1xEwZ0h+rZrFzXv9CUlLIgM5VKmGZoq8U5W0W8o1r/V8yJVgry9ZSziDxS/iIHjINYGMY",
-	"2FOQ4oGy9PAjkqWAGYT8GBNkXLEIZ8g4MoUOAllI6xhsyZDJnyxgAfQkPbyjQBgABVYJNzwgYFkV6gAt",
-	"MNriuIb28L4kfGApCeLAEVxM5DuIKWAioBUJkKMJXSDbgS0pl6wl4chKyT3cFs7gGaSkkXMHY3EbDph0",
-	"L0pRk+5AOFgeShDYYOKS4deSJfawCLBGC2sFgTkTjA6FEAa2UrzSsWhFpbngwCNny2EFGESzOebueFUc",
-	"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xOJVBb1djO7QcGPsv4Uv4TENVomRYkprPxYeYagDFo2NSkVR8D1obHusDJ/I5uw6onFVLkxxcUR+q",
+	"O3u4W2Mm51phjJSm8EpzlZcEllgsP5RGOO730XWn8Rtyk3S8oZSwO99a6wR46A6FGPhh3cPPAiM5R0Eo",
+	"67kxxlxIK2lfRD0oFbivAi26PZf7J+3Tqkx2FcjBFqEEC5I4Sz2WNixIPfxQsiUgqd1gKHyoAu0U2ZKj",
+	"xBVO8+8+wKtbClbz2OIzBvC40pTJTWr18OfSQn10qltTj0rzzhFKd2g+gMVqkbSVkz1b2pM5piZzqEY1",
+	"iwoMHLojlKlwA2feA86KwbKUgRVqzghF9j6bhGw7nZFW9+vh7lSYytyEcUwkXPxJ52qmKd2Jv7X19l/0",
+	"iNORoR53i8HMzQ8cBj1f6rGRlABKuc4g54eF4Er7PizZCSV42BodBczcPBZK2+M5r+tMN42MdSoR8vUM",
+	"upyh2gVMCbf6P8u2Hns6nNTx5hyBx6/stY0X/0BJ55lEuTipsFI9y76BybFnOQP1m8Po7l4HoDxqa6no",
+	"39zc7KceCm1aG0c3DQ6zX7NCfL6W9mujXJvjXhCxu5h/RhLYg2nT0RKLk38Iz2sw2lB/ZeMS6OuorVV7",
+	"cFvTmVy8x7S9MkAotjHmK6PG+0QodWQL9KRr97NYnWv0DG7YdYmOc87FJxouzPpuUK+aNptSlu/jsP2X",
+	"sbCfqy9puCNRj+Ew6NcBtjmdkSUV2v2TnvlNq/z3WONC8Hq/zqOzZx52zSKO5MrrV7uusZnDytV3FnhA",
+	"bbOxuWZxC7loTlc8clujm01e7WiLW+0hY9N2wjL1Dx2gj+2Dhwulv9VLrr9LXfaS7y6zViANxfCfJOTt",
+	"QYyqwhYWtwrv9ReKc8UOOi5uv3X8fL+t9/5+vZYkdv1vk+t/toxfKNrUr0sobfYynb3H71/J+5MXW307",
+	"3d3v/hYAAP//wO3O5VcSAAA=",
 }
 
 // GetSwagger returns the content of the embedded swagger specification file
diff --git a/examples/petstore-expanded/chi/api/petstore.go b/examples/petstore-expanded/chi/api/petstore.go
index 2b3dc97..ea8c34a 100644
--- a/examples/petstore-expanded/chi/api/petstore.go
+++ b/examples/petstore-expanded/chi/api/petstore.go
@@ -37,7 +37,7 @@ func sendPetstoreError(w http.ResponseWriter, code int, message string) {
 	json.NewEncoder(w).Encode(petErr)
 }
 
-// FindPets implements all the handlers in the ServerInterface
+// Here, we implement all of the handlers in the ServerInterface
 func (p *PetStore) FindPets(w http.ResponseWriter, r *http.Request, params FindPetsParams) {
 	p.Lock.Lock()
 	defer p.Lock.Unlock()
diff --git a/examples/petstore-expanded/chi/petstore.go b/examples/petstore-expanded/chi/petstore.go
index cdf725e..423950a 100644
--- a/examples/petstore-expanded/chi/petstore.go
+++ b/examples/petstore-expanded/chi/petstore.go
@@ -11,9 +11,10 @@ import (
 	"net/http"
 	"os"
 
-	"github.com/deepmap/oapi-codegen/examples/petstore-expanded/chi/api"
-	middleware "github.com/deepmap/oapi-codegen/pkg/chi-middleware"
 	"github.com/go-chi/chi/v5"
+
+	api "github.com/deepmap/oapi-codegen/examples/petstore-expanded/chi/api"
+	middleware "github.com/deepmap/oapi-codegen/pkg/chi-middleware"
 )
 
 func main() {
diff --git a/examples/petstore-expanded/echo/api/petstore-server.gen.go b/examples/petstore-expanded/echo/api/petstore-server.gen.go
index a71407f..9d4491a 100644
--- a/examples/petstore-expanded/echo/api/petstore-server.gen.go
+++ b/examples/petstore-expanded/echo/api/petstore-server.gen.go
@@ -149,29 +149,29 @@ var swaggerSpec = []string{
 	"od7rzDImj2LmhoO8fWM6I9uR2l9aUTK7znjKGVfffND+9iE0S+KwMrtdZxI9Fk40mPkvZtpwv/x+15mP",
 	"9HRHcok7oL+y3Uf0BHEJsiYYSS437Izg6jLup+34etwLoHV3hTdhQ+c+Lc38l2fz/4mWZm7+b3YUYjap",
 	"MJty2XUvk+HhEtLPgR8LAQ/nuE7F+MN3V8R4gZQHc7+73+llDsvYJA+CtuImj+zM3ODIQuj/m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V42BodBczcPBZK2+M5r+tMN42MdSoR8vUM",
+	"upyh2gVMCbf6P8u2Hns6nNTx5hyBx6/stY0X/0BJ55lEuTipsFI9y76BybFnOQP1m8Po7l4HoDxqa6no",
+	"39zc7KceCm1aG0c3DQ6zX7NCfL6W9mujXJvjXhCxu5h/RhLYg2nT0RKLk38Iz2sw2lB/ZeMS6OuorVV7",
+	"cFvTmVy8x7S9MkAotjHmK6PG+0QodWQL9KRr97NYnWv0DG7YdYmOc87FJxouzPpuUK+aNptSlu/jsP2X",
+	"sbCfqy9puCNRj+Ew6NcBtjmdkSUV2v2TnvlNq/z3WONC8Hq/zqOzZx52zSKO5MrrV7uusZnDytV3FnhA",
+	"bbOxuWZxC7loTlc8clujm01e7WiLW+0hY9N2wjL1Dx2gj+2Dhwulv9VLrr9LXfaS7y6zViANxfCfJOTt",
+	"QYyqwhYWtwrv9ReKc8UOOi5uv3X8fL+t9/5+vZYkdv1vk+t/toxfKNrUr0sobfYynb3H71/J+5MXW307",
+	"3d3v/hYAAP//wO3O5VcSAAA=",
 }
 
 // GetSwagger returns the content of the embedded swagger specification file
diff --git a/examples/petstore-expanded/echo/api/petstore.go b/examples/petstore-expanded/echo/api/petstore.go
index 70b696c..b3dfcef 100644
--- a/examples/petstore-expanded/echo/api/petstore.go
+++ b/examples/petstore-expanded/echo/api/petstore.go
@@ -22,8 +22,9 @@ import (
 	"net/http"
 	"sync"
 
-	"github.com/deepmap/oapi-codegen/examples/petstore-expanded/echo/api/models"
 	"github.com/labstack/echo/v4"
+
+	"github.com/deepmap/oapi-codegen/examples/petstore-expanded/echo/api/models"
 )
 
 type PetStore struct {
@@ -50,7 +51,7 @@ func sendPetstoreError(ctx echo.Context, code int, message string) error {
 	return err
 }
 
-// FindPets implements all the handlers in the ServerInterface
+// Here, we implement all of the handlers in the ServerInterface
 func (p *PetStore) FindPets(ctx echo.Context, params models.FindPetsParams) error {
 	p.Lock.Lock()
 	defer p.Lock.Unlock()
diff --git a/examples/petstore-expanded/gin/api/petstore-server.gen.go b/examples/petstore-expanded/gin/api/petstore-server.gen.go
index b05b843..09ec102 100644
--- a/examples/petstore-expanded/gin/api/petstore-server.gen.go
+++ b/examples/petstore-expanded/gin/api/petstore-server.gen.go
@@ -162,29 +162,29 @@ var swaggerSpec = []string{
 	"od7rzDImj2LmhoO8fWM6I9uR2l9aUTK7znjKGVfffND+9iE0S+KwMrtdZxI9Fk40mPkvZtpwv/x+15mP",
 	"9HRHcok7oL+y3Uf0BHEJsiYYSS437Izg6jLup+34etwLoHV3hTdhQ+c+Lc38l2fz/4mWZm7+b3YUYjap",
 	"MJty2XUvk+HhEtLPgR8LAQ/nuE7F+MN3V8R4gZQHc7+73+llDsvYJA+CtuImj+zM3ODIQuj/mJ9wtaLU",
-	"czTdRLH53K7Bu7sF/EToTWdK0qC1yJjns9lJ0K57kcU7yOhHRzVa1ihQMmVAzSZLTASYAQPQ17ZMIgzk",
-	"Y8iSUAiWhFISZeBQOfg0UtAnve1vII9keckW61adcWwpZDqaw7wb0a4J3vQ3F5ifnp56rLf7mFazKTbP",
-	"/rR4/+Hj5w+/e9Pf9GvxrjqGks+flp8pbdjS1cRndc1M5WBxp6zdTXmazmwo5cbK7/ub/kYfHUcKOLKZ",
-	"m7f1UmdGlHX1xEwZ0h+rZrFzXv9CUlLIgM5VKmGZoq8U5W0W8o1r/V8yJVgry9ZSziDxS/iIHjINYGMY",
-	"2FOQ4oGy9PAjkqWAGYT8GBNkXLEIZ8g4MoUOAllI6xhsyZDJnyxgAfQkPbyjQBgABVYJNzwgYFkV6gAt",
-	"MNriuIb28L4kfGApCeLAEVxM5DuIKWAioBUJkKMJXSDbgS0pl6wl4chKyT3cFs7gGaSkkXMHY3EbDph0",
-	"L0pRk+5AOFgeShDYYOKS4deSJfawCLBGC2sFgTkTjA6FEAa2UrzSsWhFpbngwCNny2EFGESzOebueFUc",
-	"HjIf15hIEu5J1PXgo6MsTMB+pDSwMvVX3qBvCaHjx4IeBkZlJmGGR81tQ44FQg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FVLkxxcUR+q",
+	"O3u4W2Mm51phjJSm8EpzlZcEllgsP5RGOO730XWn8Rtyk3S8oZSwO99a6wR46A6FGPhh3cPPAiM5R0Eo",
+	"67kxxlxIK2lfRD0oFbivAi26PZf7J+3Tqkx2FcjBFqEEC5I4Sz2WNixIPfxQsiUgqd1gKHyoAu0U2ZKj",
+	"xBVO8+8+wKtbClbz2OIzBvC40pTJTWr18OfSQn10qltTj0rzzhFKd2g+gMVqkbSVkz1b2pM5piZzqEY1",
+	"iwoMHLojlKlwA2feA86KwbKUgRVqzghF9j6bhGw7nZFW9+vh7lSYytyEcUwkXPxJ52qmKd2Jv7X19l/0",
+	"iNORoR53i8HMzQ8cBj1f6rGRlABKuc4g54eF4Er7PizZCSV42BodBczcPBZK2+M5r+tMN42MdSoR8vUM",
+	"upyh2gVMCbf6P8u2Hns6nNTx5hyBx6/stY0X/0BJ55lEuTipsFI9y76BybFnOQP1m8Po7l4HoDxqa6no",
+	"39zc7KceCm1aG0c3DQ6zX7NCfL6W9mujXJvjXhCxu5h/RhLYg2nT0RKLk38Iz2sw2lB/ZeMS6OuorVV7",
+	"cFvTmVy8x7S9MkAotjHmK6PG+0QodWQL9KRr97NYnWv0DG7YdYmOc87FJxouzPpuUK+aNptSlu/jsP2X",
+	"sbCfqy9puCNRj+Ew6NcBtjmdkSUV2v2TnvlNq/z3WONC8Hq/zqOzZx52zSKO5MrrV7uusZnDytV3FnhA",
+	"bbOxuWZxC7loTlc8clujm01e7WiLW+0hY9N2wjL1Dx2gj+2Dhwulv9VLrr9LXfaS7y6zViANxfCfJOTt",
+	"QYyqwhYWtwrv9ReKc8UOOi5uv3X8fL+t9/5+vZYkdv1vk+t/toxfKNrUr0sobfYynb3H71/J+5MXW307",
+	"3d3v/hYAAP//wO3O5VcSAAA=",
 }
 
 // GetSwagger returns the content of the embedded swagger specification file
diff --git a/examples/petstore-expanded/gin/api/petstore.go b/examples/petstore-expanded/gin/api/petstore.go
index f79d282..f36fcf0 100644
--- a/examples/petstore-expanded/gin/api/petstore.go
+++ b/examples/petstore-expanded/gin/api/petstore.go
@@ -48,7 +48,7 @@ func sendPetstoreError(c *gin.Context, code int, message string) {
 	c.JSON(code, petErr)
 }
 
-// FindPets implements all the handlers in the ServerInterface
+// Here, we implement all of the handlers in the ServerInterface
 func (p *PetStore) FindPets(c *gin.Context, params FindPetsParams) {
 	p.Lock.Lock()
 	defer p.Lock.Unlock()
diff --git a/examples/petstore-expanded/gin/petstore.go b/examples/petstore-expanded/gin/petstore.go
index 2eae15b..a08f5ce 100644
--- a/examples/petstore-expanded/gin/petstore.go
+++ b/examples/petstore-expanded/gin/petstore.go
@@ -11,9 +11,10 @@ import (
 	"net/http"
 	"os"
 
+	"github.com/gin-gonic/gin"
+
 	"github.com/deepmap/oapi-codegen/examples/petstore-expanded/gin/api"
 	middleware "github.com/deepmap/oapi-codegen/pkg/gin-middleware"
-	"github.com/gin-gonic/gin"
 )
 
 func NewGinPetServer(petStore *api.PetStore, port int) *http.Server {
diff --git a/examples/petstore-expanded/gorilla/api/petstore.gen.go b/examples/petstore-expanded/gorilla/api/petstore.gen.go
index b56e03c..56762c5 100644
--- a/examples/petstore-expanded/gorilla/api/petstore.gen.go
+++ b/examples/petstore-expanded/gorilla/api/petstore.gen.go
@@ -320,29 +320,29 @@ var swaggerSpec = []string{
 	"od7rzDImj2LmhoO8fWM6I9uR2l9aUTK7znjKGVfffND+9iE0S+KwMrtdZxI9Fk40mPkvZtpwv/x+15mP",
 	"9HRHcok7oL+y3Uf0BHEJsiYYSS437Izg6jLup+34etwLoHV3hTdhQ+c+Lc38l2fz/4mWZm7+b3YUYjap",
 	"MJty2XUvk+HhEtLPgR8LAQ/nuE7F+MN3V8R4gZQHc7+73+llDsvYJA+CtuImj+zM3ODIQuj/mJ9wtaLU",
-	"czTdRLH53K7Bu7sF/EToTWdK0qC1yJjns9lJ0K57kcU7yOhHRzVa1ihQMmVAzSZLTASYAQPQ17ZMIgzk",
-	"Y8iSUAiWhFISZe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",
+	"39zc7KceCm1aG0c3DQ6zX7NCfL6W9mujXJvjXhCxu5h/RhLYg2nT0RKLk38Iz2sw2lB/ZeMS6OuorVV7",
+	"cFvTmVy8x7S9MkAotjHmK6PG+0QodWQL9KRr97NYnWv0DG7YdYmOc87FJxouzPpuUK+aNptSlu/jsP2X",
+	"sbCfqy9puCNRj+Ew6NcBtjmdkSUV2v2TnvlNq/z3WONC8Hq/zqOzZx52zSKO5MrrV7uusZnDytV3FnhA",
+	"bbOxuWZxC7loTlc8clujm01e7WiLW+0hY9N2wjL1Dx2gj+2Dhwulv9VLrr9LXfaS7y6zViANxfCfJOTt",
+	"QYyqwhYWtwrv9ReKc8UOOi5uv3X8fL+t9/5+vZYkdv1vk+t/toxfKNrUr0sobfYynb3H71/J+5MXW307",
+	"3d3v/hYAAP//wO3O5VcSAAA=",
 }
 
 // GetSwagger returns the content of the embedded swagger specification file
diff --git a/examples/petstore-expanded/gorilla/api/petstore.go b/examples/petstore-expanded/gorilla/api/petstore.go
index 2b3dc97..ea8c34a 100644
--- a/examples/petstore-expanded/gorilla/api/petstore.go
+++ b/examples/petstore-expanded/gorilla/api/petstore.go
@@ -37,7 +37,7 @@ func sendPetstoreError(w http.ResponseWriter, code int, message string) {
 	json.NewEncoder(w).Encode(petErr)
 }
 
-// FindPets implements all the handlers in the ServerInterface
+// Here, we implement all of the handlers in the ServerInterface
 func (p *PetStore) FindPets(w http.ResponseWriter, r *http.Request, params FindPetsParams) {
 	p.Lock.Lock()
 	defer p.Lock.Unlock()
diff --git a/examples/petstore-expanded/gorilla/petstore.go b/examples/petstore-expanded/gorilla/petstore.go
index dfd0118..b31239b 100644
--- a/examples/petstore-expanded/gorilla/petstore.go
+++ b/examples/petstore-expanded/gorilla/petstore.go
@@ -11,7 +11,7 @@ import (
 	"net/http"
 	"os"
 
-	"github.com/deepmap/oapi-codegen/examples/petstore-expanded/gorilla/api"
+	api "github.com/deepmap/oapi-codegen/examples/petstore-expanded/gorilla/api"
 	middleware "github.com/deepmap/oapi-codegen/pkg/chi-middleware"
 	"github.com/gorilla/mux"
 )
diff --git a/examples/petstore-expanded/petstore-expanded.yaml b/examples/petstore-expanded/petstore-expanded.yaml
index f9f84f2..53fdad5 100644
--- a/examples/petstore-expanded/petstore-expanded.yaml
+++ b/examples/petstore-expanded/petstore-expanded.yaml
@@ -3,16 +3,16 @@ info:
   version: 1.0.0
   title: Swagger Petstore
   description: A sample API that uses a petstore as an example to demonstrate features in the OpenAPI 3.0 specification
-  termsOfService: https://swagger.io/terms/
+  termsOfService: http://swagger.io/terms/
   contact:
     name: Swagger API Team
     email: apiteam@swagger.io
-    url: https://swagger.io
+    url: http://swagger.io
   license:
     name: Apache 2.0
     url: https://www.apache.org/licenses/LICENSE-2.0.html
 servers:
-  - url: https://petstore.swagger.io/api
+  - url: http://petstore.swagger.io/api
 paths:
   /pets:
     get:
@@ -132,7 +132,7 @@ components:
       allOf:
         - $ref: '#/components/schemas/NewPet'
         - required:
-            - id
+          - id
           properties:
             id:
               type: integer
diff --git a/examples/petstore-expanded/strict/api/petstore-server.gen.go b/examples/petstore-expanded/strict/api/petstore-server.gen.go
index 8901ebb..7164d5d 100644
--- a/examples/petstore-expanded/strict/api/petstore-server.gen.go
+++ b/examples/petstore-expanded/strict/api/petstore-server.gen.go
@@ -555,29 +555,29 @@ var swaggerSpec = []string{
 	"od7rzDImj2LmhoO8fWM6I9uR2l9aUTK7znjKGVfffND+9iE0S+KwMrtdZxI9Fk40mPkvZtpwv/x+15mP",
 	"9HRHcok7oL+y3Uf0BHEJsiYYSS437Izg6jLup+34etwLoHV3hTdhQ+c+Lc38l2fz/4mWZm7+b3YUYjap",
 	"MJty2XUvk+HhEtLPgR8LAQ/nuE7F+MN3V8R4gZQHc7+73+llDsvYJA+CtuImj+zM3ODIQuj/mJ9wtaLU",
-	"czTdRLH53K7Bu7sF/EToTWdK0qC1yJjns9lJ0K57kcU7yOhHRzVa1ihQMmVAzSZLTASYAQPQ17ZMIgzk",
-	"Y8i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l4HoDxqa6no",
+	"39zc7KceCm1aG0c3DQ6zX7NCfL6W9mujXJvjXhCxu5h/RhLYg2nT0RKLk38Iz2sw2lB/ZeMS6OuorVV7",
+	"cFvTmVy8x7S9MkAotjHmK6PG+0QodWQL9KRr97NYnWv0DG7YdYmOc87FJxouzPpuUK+aNptSlu/jsP2X",
+	"sbCfqy9puCNRj+Ew6NcBtjmdkSUV2v2TnvlNq/z3WONC8Hq/zqOzZx52zSKO5MrrV7uusZnDytV3FnhA",
+	"bbOxuWZxC7loTlc8clujm01e7WiLW+0hY9N2wjL1Dx2gj+2Dhwulv9VLrr9LXfaS7y6zViANxfCfJOTt",
+	"QYyqwhYWtwrv9ReKc8UOOi5uv3X8fL+t9/5+vZYkdv1vk+t/toxfKNrUr0sobfYynb3H71/J+5MXW307",
+	"3d3v/hYAAP//wO3O5VcSAAA=",
 }
 
 // GetSwagger returns the content of the embedded swagger specification file
diff --git a/examples/petstore-expanded/strict/api/petstore.go b/examples/petstore-expanded/strict/api/petstore.go
index dc2c301..3973bf5 100644
--- a/examples/petstore-expanded/strict/api/petstore.go
+++ b/examples/petstore-expanded/strict/api/petstore.go
@@ -27,7 +27,7 @@ func NewPetStore() *PetStore {
 	}
 }
 
-// FindPets implements all the handlers in the ServerInterface
+// Here, we implement all of the handlers in the ServerInterface
 func (p *PetStore) FindPets(ctx context.Context, request FindPetsRequestObject) (FindPetsResponseObject, error) {
 	p.Lock.Lock()
 	defer p.Lock.Unlock()
diff --git a/examples/petstore-expanded/strict/petstore.go b/examples/petstore-expanded/strict/petstore.go
index c348600..4e33e9e 100644
--- a/examples/petstore-expanded/strict/petstore.go
+++ b/examples/petstore-expanded/strict/petstore.go
@@ -11,9 +11,10 @@ import (
 	"net/http"
 	"os"
 
+	"github.com/go-chi/chi/v5"
+
 	"github.com/deepmap/oapi-codegen/examples/petstore-expanded/strict/api"
 	middleware "github.com/deepmap/oapi-codegen/pkg/chi-middleware"
-	"github.com/go-chi/chi/v5"
 )
 
 func main() {
diff --git a/go.mod b/go.mod
index c06974e..03b34af 100644
--- a/go.mod
+++ b/go.mod
@@ -2,6 +2,7 @@ module github.com/deepmap/oapi-codegen
 
 require (
 	github.com/apapsch/go-jsonmerge/v2 v2.0.0
+	github.com/cyberdelia/templates v1.0.0
 	github.com/getkin/kin-openapi v0.104.0
 	github.com/gin-gonic/gin v1.8.1
 	github.com/go-chi/chi/v5 v5.0.7
diff --git a/go.sum b/go.sum
index ad12a43..72b6607 100644
--- a/go.sum
+++ b/go.sum
@@ -3,6 +3,8 @@ github.com/apapsch/go-jsonmerge/v2 v2.0.0 h1:axGnT1gRIfimI7gJifB699GoE/oq+F2MU7D
 github.com/apapsch/go-jsonmerge/v2 v2.0.0/go.mod h1:lvDnEdqiQrp0O42VQGgmlKpxL1AP2+08jFMw88y4klk=
 github.com/bmatcuk/doublestar v1.1.1/go.mod h1:UD6OnuiIn0yFxxA2le/rnRU1G4RaI4UvFv1sNto9p6w=
 github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
+github.com/cyberdelia/templates v1.0.0 h1:9QMxMNj0deS+mhdrlpqJdjKgKyj3y6o44JABXL237ZA=
+github.com/cyberdelia/templates v1.0.0/go.mod h1:FP2410OYqQxXlUvpRmWfR8C5nxMmviRI8wK7vseMqZc=
 github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
 github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
 github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
diff --git a/pkg/chi-middleware/oapi_validate.go b/pkg/chi-middleware/oapi_validate.go
index 8c37a79..e230239 100644
--- a/pkg/chi-middleware/oapi_validate.go
+++ b/pkg/chi-middleware/oapi_validate.go
@@ -125,7 +125,7 @@ func getMultiErrorHandlerFromOptions(options *Options) MultiErrorHandler {
 }
 
 // defaultMultiErrorHandler returns a StatusBadRequest (400) and a list
-// of all the errors. This method is called if there are no other
+// of all of the errors. This method is called if there are no other
 // methods defined on the options.
 func defaultMultiErrorHandler(me openapi3.MultiError) (int, error) {
 	return http.StatusBadRequest, me
diff --git a/pkg/codegen/codegen.go b/pkg/codegen/codegen.go
index c4f3847..7d03752 100644
--- a/pkg/codegen/codegen.go
+++ b/pkg/codegen/codegen.go
@@ -30,7 +30,6 @@ import (
 )
 
 // Embed the templates directory
-//
 //go:embed templates
 var templates embed.FS
 
@@ -139,12 +138,8 @@ func Generate(spec *openapi3.T, opts Configuration) (string, error) {
 		return "", fmt.Errorf("error creating operation definitions: %w", err)
 	}
 
-	xGoTypeImports, err := OperationImports(ops)
-	if err != nil {
-		return "", fmt.Errorf("error getting operation imports: %w", err)
-	}
-
 	var typeDefinitions, constantDefinitions string
+	var xGoTypeImports map[string]goImport
 	if opts.Generate.Models {
 		typeDefinitions, err = GenerateTypeDefinitions(t, spec, ops, opts.OutputOptions.ExcludeSchemas)
 		if err != nil {
@@ -156,11 +151,10 @@ func Generate(spec *openapi3.T, opts Configuration) (string, error) {
 			return "", fmt.Errorf("error generating constants: %w", err)
 		}
 
-		imprts, err := GetTypeDefinitionsImports(spec, opts.OutputOptions.ExcludeSchemas)
+		xGoTypeImports, err = GetTypeDefinitionsImports(spec, opts.OutputOptions.ExcludeSchemas)
 		if err != nil {
 			return "", fmt.Errorf("error getting type definition imports: %w", err)
 		}
-		MergeImports(xGoTypeImports, imprts)
 	}
 
 	var echoServerOut string
@@ -396,7 +390,7 @@ func GenerateTypeDefinitions(t *template.Template, swagger *openapi3.T, ops []Op
 	return typeDefinitions, nil
 }
 
-// GenerateConstants generates operation ids, context keys, paths, etc. to be exported as constants
+// Generates operation ids, context keys, paths, etc. to be exported as constants
 func GenerateConstants(t *template.Template, ops []OperationDefinition) (string, error) {
 	constants := Constants{
 		SecuritySchemeProviderNames: []string{},
@@ -683,7 +677,7 @@ func GenerateEnums(t *template.Template, types []TypeDefinition) (string, error)
 	return GenerateTemplates([]string{"constants.tmpl"}, t, Constants{EnumDefinitions: enums})
 }
 
-// GenerateImports generates our import statements and package definition.
+// Generate our import statements and package definition.
 func GenerateImports(t *template.Template, externalImports []string, packageName string) (string, error) {
 	// Read build version for incorporating into generated files
 	// Unit tests have ok=false, so we'll just use "unknown" for the
@@ -800,60 +794,6 @@ func LoadTemplates(src embed.FS, t *template.Template) error {
 	})
 }
 
-func OperationSchemaImports(s *Schema) (map[string]goImport, error) {
-	res := map[string]goImport{}
-
-	for _, p := range s.Properties {
-		imprts, err := GoSchemaImports(&openapi3.SchemaRef{Value: p.Schema.OAPISchema})
-		if err != nil {
-			return nil, err
-		}
-		MergeImports(res, imprts)
-	}
-
-	imprts, err := GoSchemaImports(&openapi3.SchemaRef{Value: s.OAPISchema})
-	if err != nil {
-		return nil, err
-	}
-	MergeImports(res, imprts)
-	return res, nil
-}
-
-func OperationImports(ops []OperationDefinition) (map[string]goImport, error) {
-	res := map[string]goImport{}
-	for _, op := range ops {
-		for _, pd := range [][]ParameterDefinition{op.PathParams, op.QueryParams} {
-			for _, p := range pd {
-				imprts, err := OperationSchemaImports(&p.Schema)
-				if err != nil {
-					return nil, err
-				}
-				MergeImports(res, imprts)
-			}
-		}
-
-		for _, b := range op.Bodies {
-			imprts, err := OperationSchemaImports(&b.Schema)
-			if err != nil {
-				return nil, err
-			}
-			MergeImports(res, imprts)
-		}
-
-		for _, b := range op.Responses {
-			for _, c := range b.Contents {
-				imprts, err := OperationSchemaImports(&c.Schema)
-				if err != nil {
-					return nil, err
-				}
-				MergeImports(res, imprts)
-			}
-		}
-
-	}
-	return res, nil
-}
-
 func GetTypeDefinitionsImports(swagger *openapi3.T, excludeSchemas []string) (map[string]goImport, error) {
 	res := map[string]goImport{}
 	schemaImports, err := GetSchemaImports(swagger.Components.Schemas, excludeSchemas)
@@ -871,48 +811,9 @@ func GetTypeDefinitionsImports(swagger *openapi3.T, excludeSchemas []string) (ma
 		return nil, err
 	}
 
-	parametersImports, err := GetParametersImports(swagger.Components.Parameters)
-	if err != nil {
-		return nil, err
-	}
-
-	for _, imprts := range []map[string]goImport{schemaImports, reqBodiesImports, responsesImports, parametersImports} {
-		MergeImports(res, imprts)
-	}
-	return res, nil
-}
-
-func GoSchemaImports(schemas ...*openapi3.SchemaRef) (map[string]goImport, error) {
-	res := map[string]goImport{}
-	for _, sref := range schemas {
-		if sref == nil || sref.Value == nil || IsGoTypeReference(sref.Ref) {
-			return nil, nil
-		}
-		if gi, err := ParseGoImportExtension(sref); err != nil {
-			return nil, err
-		} else {
-			if gi != nil {
-				res[gi.String()] = *gi
-			}
-		}
-		schemaVal := sref.Value
-
-		t := schemaVal.Type
-		switch t {
-		case "", "object":
-			for _, v := range schemaVal.Properties {
-				imprts, err := GoSchemaImports(v)
-				if err != nil {
-					return nil, err
-				}
-				MergeImports(res, imprts)
-			}
-		case "array":
-			imprts, err := GoSchemaImports(schemaVal.Items)
-			if err != nil {
-				return nil, err
-			}
-			MergeImports(res, imprts)
+	for _, imprts := range []map[string]goImport{schemaImports, reqBodiesImports, responsesImports} {
+		for k, v := range imprts {
+			res[k] = v
 		}
 	}
 	return res, nil
@@ -924,31 +825,48 @@ func GetSchemaImports(schemas map[string]*openapi3.SchemaRef, excludeSchemas []s
 	for _, schema := range excludeSchemas {
 		excludeSchemasMap[schema] = true
 	}
-	for schemaName, schema := range schemas {
+	for _, schemaName := range SortedSchemaKeys(schemas) {
 		if _, ok := excludeSchemasMap[schemaName]; ok {
 			continue
 		}
+		schema := schemas[schemaName].Value
 
-		imprts, err := GoSchemaImports(schema)
+		if schema == nil || schema.Properties == nil {
+			continue
+		}
+
+		imprts, err := GetImports(schema.Properties)
 		if err != nil {
 			return nil, err
 		}
-		MergeImports(res, imprts)
+
+		for s, gi := range imprts {
+			res[s] = gi
+		}
 	}
 	return res, nil
 }
 
 func GetRequestBodiesImports(bodies map[string]*openapi3.RequestBodyRef) (map[string]goImport, error) {
 	res := map[string]goImport{}
-	for _, r := range bodies {
-		response := r.Value
+	for _, requestBodyName := range SortedRequestBodyKeys(bodies) {
+		requestBodyRef := bodies[requestBodyName]
+		response := requestBodyRef.Value
 		jsonBody, found := response.Content["application/json"]
 		if found {
-			imprts, err := GoSchemaImports(jsonBody.Schema)
+			schema := jsonBody.Schema
+			if schema == nil || schema.Value == nil || schema.Value.Properties == nil {
+				continue
+			}
+
+			imprts, err := GetImports(schema.Value.Properties)
 			if err != nil {
 				return nil, err
 			}
-			MergeImports(res, imprts)
+
+			for s, gi := range imprts {
+				res[s] = gi
+			}
 		}
 	}
 	return res, nil
@@ -956,31 +874,25 @@ func GetRequestBodiesImports(bodies map[string]*openapi3.RequestBodyRef) (map[st
 
 func GetResponsesImports(responses map[string]*openapi3.ResponseRef) (map[string]goImport, error) {
 	res := map[string]goImport{}
-	for _, r := range responses {
-		response := r.Value
+	for _, responseName := range SortedResponsesKeys(responses) {
+		responseOrRef := responses[responseName]
+		response := responseOrRef.Value
 		jsonResponse, found := response.Content["application/json"]
 		if found {
-			imprts, err := GoSchemaImports(jsonResponse.Schema)
+			schema := jsonResponse.Schema
+			if schema == nil || schema.Value == nil || schema.Value.Properties == nil {
+				continue
+			}
+
+			imprts, err := GetImports(schema.Value.Properties)
 			if err != nil {
 				return nil, err
 			}
-			MergeImports(res, imprts)
-		}
-	}
-	return res, nil
-}
 
-func GetParametersImports(params map[string]*openapi3.ParameterRef) (map[string]goImport, error) {
-	res := map[string]goImport{}
-	for _, param := range params {
-		if param.Value == nil {
-			continue
-		}
-		imprts, err := GoSchemaImports(param.Value.Schema)
-		if err != nil {
-			return nil, err
+			for s, gi := range imprts {
+				res[s] = gi
+			}
 		}
-		MergeImports(res, imprts)
 	}
 	return res, nil
 }
diff --git a/pkg/codegen/configuration.go b/pkg/codegen/configuration.go
index df8fa73..290c139 100644
--- a/pkg/codegen/configuration.go
+++ b/pkg/codegen/configuration.go
@@ -64,11 +64,6 @@ type CompatibilityOptions struct {
 	// When set to true, always prefix enum values with their type name instead of only
 	// when typenames would be conflicting.
 	AlwaysPrefixEnumValues bool `yaml:"always-prefix-enum-values,omitempty"`
-	// Our generated code for Chi has historically inverted the order in which Chi middleware is
-	// applied such that the last invoked middleware ends up executing first in the Chi chain
-	// This resolves the behavior such that middlewares are chained in the order they are invoked.
-	// Please see https://github.com/deepmap/oapi-codegen/issues/786
-	ApplyChiMiddlewareFirstToLast bool `yaml:"apply-chi-middleware-first-to-last,omitempty"`
 }
 
 // OutputOptions are used to modify the output code in some way.
diff --git a/pkg/codegen/extension.go b/pkg/codegen/extension.go
index 5d01c78..a9ee43d 100644
--- a/pkg/codegen/extension.go
+++ b/pkg/codegen/extension.go
@@ -6,7 +6,6 @@ import (
 )
 
 const (
-	extPropGoImport     = "x-go-type-import"
 	extPropGoType       = "x-go-type"
 	extGoName           = "x-go-name"
 	extPropGoJsonIgnore = "x-go-json-ignore"
diff --git a/pkg/codegen/filter.go b/pkg/codegen/filter.go
index 01a3639..56c9730 100644
--- a/pkg/codegen/filter.go
+++ b/pkg/codegen/filter.go
@@ -30,7 +30,7 @@ func includeOperationsWithTags(paths openapi3.Paths, tags []string, exclude bool
 	}
 }
 
-// operationHasTag returns true if the operation is tagged with any of tags
+//operationHasTag returns true if the operation is tagged with any of tags
 func operationHasTag(op *openapi3.Operation, tags []string) bool {
 	if op == nil {
 		return false
diff --git a/pkg/codegen/inline.go b/pkg/codegen/inline.go
index eedafa7..cbd916c 100644
--- a/pkg/codegen/inline.go
+++ b/pkg/codegen/inline.go
@@ -16,6 +16,7 @@ package codegen
 import (
 	"bytes"
 	"compress/gzip"
+	"context"
 	"encoding/base64"
 	"fmt"
 	"text/template"
@@ -23,9 +24,11 @@ import (
 	"github.com/getkin/kin-openapi/openapi3"
 )
 
-// GenerateInlinedSpec generates a gzipped, base64 encoded JSON representation of the
+// This generates a gzipped, base64 encoded JSON representation of the
 // swagger definition, which we embed inside the generated code.
 func GenerateInlinedSpec(t *template.Template, importMapping importMap, swagger *openapi3.T) (string, error) {
+	// ensure that any external file references are embedded into the embedded spec
+	swagger.InternalizeRefs(context.Background(), nil)
 	// Marshal to json
 	encoded, err := swagger.MarshalJSON()
 	if err != nil {
diff --git a/pkg/codegen/merge_schemas.go b/pkg/codegen/merge_schemas.go
index a6fbb33..1ac358d 100644
--- a/pkg/codegen/merge_schemas.go
+++ b/pkg/codegen/merge_schemas.go
@@ -13,7 +13,7 @@ func MergeSchemas(allOf []*openapi3.SchemaRef, path []string) (Schema, error) {
 	// If someone asked for the old way, for backward compatibility, return the
 	// old style result.
 	if globalState.options.Compatibility.OldMergeSchemas {
-		return mergeSchemasV1(allOf, path)
+		return mergeSchemas_V1(allOf, path)
 	}
 	return mergeSchemas(allOf, path)
 }
diff --git a/pkg/codegen/merge_schemas_v1.go b/pkg/codegen/merge_schemas_v1.go
index af83582..ae2f125 100644
--- a/pkg/codegen/merge_schemas_v1.go
+++ b/pkg/codegen/merge_schemas_v1.go
@@ -8,7 +8,7 @@ import (
 	"github.com/getkin/kin-openapi/openapi3"
 )
 
-func mergeSchemasV1(allOf []*openapi3.SchemaRef, path []string) (Schema, error) {
+func mergeSchemas_V1(allOf []*openapi3.SchemaRef, path []string) (Schema, error) {
 	var outSchema Schema
 	for _, schemaOrRef := range allOf {
 		ref := schemaOrRef.Ref
@@ -60,7 +60,7 @@ func mergeSchemasV1(allOf []*openapi3.SchemaRef, path []string) (Schema, error)
 	return outSchema, nil
 }
 
-// GenStructFromAllOf generates an object that is the union of the objects in the
+// This function generates an object that is the union of the objects in the
 // input array. In the case of Ref objects, we use an embedded struct, otherwise,
 // we inline the fields.
 func GenStructFromAllOf(allOf []*openapi3.SchemaRef, path []string) (string, error) {
diff --git a/pkg/codegen/operations.go b/pkg/codegen/operations.go
index ff1ea9c..3aa64ac 100644
--- a/pkg/codegen/operations.go
+++ b/pkg/codegen/operations.go
@@ -35,7 +35,7 @@ type ParameterDefinition struct {
 	Schema    Schema
 }
 
-// TypeDef is here as an adapter after a large refactoring so that I don't
+// This function is here as an adapter after a large refactoring so that I don't
 // have to update all the templates. It returns the type definition for a parameter,
 // without the leading '*' for optional ones.
 func (pd ParameterDefinition) TypeDef() string {
@@ -43,7 +43,7 @@ func (pd ParameterDefinition) TypeDef() string {
 	return typeDecl
 }
 
-// JsonTag generates the JSON annotation to map GoType to json type name. If Parameter
+// Generate the JSON annotation to map GoType to json type name. If Parameter
 // Foo is marshaled to json as "foo", this will create the annotation
 // 'json:"foo"'
 func (pd *ParameterDefinition) JsonTag() string {
@@ -149,7 +149,7 @@ func (p ParameterDefinitions) FindByName(name string) *ParameterDefinition {
 	return nil
 }
 
-// DescribeParameters walks the given parameters dictionary, and generates the above
+// This function walks the given parameters dictionary, and generates the above
 // descriptors into a flat list. This makes it a lot easier to traverse the
 // data in the template engine.
 func DescribeParameters(params openapi3.Parameters, path []string) ([]ParameterDefinition, error) {
@@ -205,7 +205,7 @@ func DescribeSecurityDefinition(securityRequirements openapi3.SecurityRequiremen
 	return outDefs
 }
 
-// OperationDefinition describes an Operation
+// This structure describes an Operation
 type OperationDefinition struct {
 	OperationId string // The operation_id description from Swagger, used to generate function names
 
@@ -224,7 +224,7 @@ type OperationDefinition struct {
 	Spec                *openapi3.Operation
 }
 
-// Params returns the list of all parameters except Path parameters. Path parameters
+// Returns the list of all parameters except Path parameters. Path parameters
 // are handled differently from the rest, since they're mandatory.
 func (o *OperationDefinition) Params() []ParameterDefinition {
 	result := append(o.QueryParams, o.HeaderParams...)
@@ -232,7 +232,7 @@ func (o *OperationDefinition) Params() []ParameterDefinition {
 	return result
 }
 
-// AllParams returns all parameters
+// Returns all parameters
 func (o *OperationDefinition) AllParams() []ParameterDefinition {
 	result := append(o.QueryParams, o.HeaderParams...)
 	result = append(result, o.CookieParams...)
@@ -247,14 +247,14 @@ func (o *OperationDefinition) RequiresParamObject() bool {
 	return len(o.Params()) > 0
 }
 
-// HasBody is called by the template engine to determine whether to generate body
-// marshaling code on the client. This is true for all body types, whether
-// we generate types for them.
+// This is called by the template engine to determine whether to generate body
+// marshaling code on the client. This is true for all body types, whether or
+// not we generate types for them.
 func (o *OperationDefinition) HasBody() bool {
 	return o.Spec.RequestBody != nil
 }
 
-// SummaryAsComment returns the Operations summary as a multi line comment
+// This returns the Operations summary as a multi line comment
 func (o *OperationDefinition) SummaryAsComment() string {
 	if o.Summary == "" {
 		return ""
@@ -267,7 +267,7 @@ func (o *OperationDefinition) SummaryAsComment() string {
 	return strings.Join(parts, "\n")
 }
 
-// GetResponseTypeDefinitions produces a list of type definitions for a given Operation for the response
+// Produces a list of type definitions for a given Operation for the response
 // types which we know how to parse. These will be turned into fields on a
 // response object for automatic deserialization of responses in the generated
 // Client code. See "client-with-responses.tmpl".
@@ -337,7 +337,7 @@ func (o OperationDefinition) HasMaskedRequestContentTypes() bool {
 	return false
 }
 
-// RequestBodyDefinition describes a request body
+// This describes a request body
 type RequestBodyDefinition struct {
 	// Is this body required, or optional?
 	Required bool
@@ -360,7 +360,7 @@ type RequestBodyDefinition struct {
 	Encoding map[string]RequestBodyEncoding
 }
 
-// TypeDef returns the Go type definition for a request body
+// Returns the Go type definition for a request body
 func (r RequestBodyDefinition) TypeDef(opID string) *TypeDefinition {
 	return &TypeDefinition{
 		TypeName: fmt.Sprintf("%s%sRequestBody", opID, r.NameTag),
@@ -368,7 +368,7 @@ func (r RequestBodyDefinition) TypeDef(opID string) *TypeDefinition {
 	}
 }
 
-// CustomType returns whether the body is a custom inline type, or pre-defined. This is
+// Returns whether the body is a custom inline type, or pre-defined. This is
 // poorly named, but it's here for compatibility reasons post-refactoring
 // TODO: clean up the templates code, it can be simpler.
 func (r RequestBodyDefinition) CustomType() bool {
@@ -386,17 +386,17 @@ func (r RequestBodyDefinition) Suffix() string {
 	return "With" + r.NameTag + "Body"
 }
 
-// IsSupportedByClient returns true if we support this content type for client. Otherwise only generic method will ge generated
+// Returns true if we support this content type for client. Otherwise only generic method will ge generated
 func (r RequestBodyDefinition) IsSupportedByClient() bool {
 	return r.NameTag == "JSON" || r.NameTag == "Formdata" || r.NameTag == "Text"
 }
 
-// IsSupported returns true if we support this content type for server. Otherwise io.Reader will be generated
+// Returns true if we support this content type for server. Otherwise io.Reader will be generated
 func (r RequestBodyDefinition) IsSupported() bool {
 	return r.NameTag != ""
 }
 
-// IsFixedContentType returns true if content type has fixed content type, i.e. contains no "*" symbol
+// Returns true if content type has fixed content type, i.e. contains no "*" symbol
 func (r RequestBodyDefinition) IsFixedContentType() bool {
 	return !strings.Contains(r.ContentType, "*")
 }
@@ -452,7 +452,7 @@ func (r ResponseContentDefinition) IsSupported() bool {
 	return r.NameTag != ""
 }
 
-// HasFixedContentType returns true if content type has fixed content type, i.e. contains no "*" symbol
+// Returns true if content type has fixed content type, i.e. contains no "*" symbol
 func (r ResponseContentDefinition) HasFixedContentType() bool {
 	return !strings.Contains(r.ContentType, "*")
 }
@@ -470,7 +470,7 @@ type ResponseHeaderDefinition struct {
 	Schema Schema
 }
 
-// FilterParameterDefinitionByType returns the subset of the specified parameters which are of the
+// This function returns the subset of the specified parameters which are of the
 // specified type.
 func FilterParameterDefinitionByType(params []ParameterDefinition, in string) []ParameterDefinition {
 	var out []ParameterDefinition
@@ -589,7 +589,7 @@ func OperationDefinitions(swagger *openapi3.T) ([]OperationDefinition, error) {
 }
 
 func generateDefaultOperationID(opName string, requestPath string) (string, error) {
-	var operationId = strings.ToLower(opName)
+	var operationId string = strings.ToLower(opName)
 
 	if opName == "" {
 		return "", fmt.Errorf("operation name cannot be an empty string")
@@ -608,7 +608,7 @@ func generateDefaultOperationID(opName string, requestPath string) (string, erro
 	return ToCamelCase(operationId), nil
 }
 
-// GenerateBodyDefinitions turns the Swagger body definitions into a list of our body
+// This function turns the Swagger body definitions into a list of our body
 // definitions which will be used for code generation.
 func GenerateBodyDefinitions(operationID string, bodyOrRef *openapi3.RequestBodyRef) ([]RequestBodyDefinition, []TypeDefinition, error) {
 	if bodyOrRef == nil {
@@ -897,13 +897,13 @@ func GenerateEchoServer(t *template.Template, operations []OperationDefinition)
 	return GenerateTemplates([]string{"echo/echo-interface.tmpl", "echo/echo-wrappers.tmpl", "echo/echo-register.tmpl"}, t, operations)
 }
 
-// GenerateGinServer generates all the go code for the ServerInterface as well as
+// GenerateGinServer This function generates all the go code for the ServerInterface as well as
 // all the wrapper functions around our handlers.
 func GenerateGinServer(t *template.Template, operations []OperationDefinition) (string, error) {
 	return GenerateTemplates([]string{"gin/gin-interface.tmpl", "gin/gin-wrappers.tmpl", "gin/gin-register.tmpl"}, t, operations)
 }
 
-// GenerateGorillaServer generates all the go code for the ServerInterface as well as
+// GenerateGinServer This function generates all the go code for the ServerInterface as well as
 // all the wrapper functions around our handlers.
 func GenerateGorillaServer(t *template.Template, operations []OperationDefinition) (string, error) {
 	return GenerateTemplates([]string{"gorilla/gorilla-interface.tmpl", "gorilla/gorilla-middleware.tmpl", "gorilla/gorilla-register.tmpl"}, t, operations)
@@ -927,13 +927,13 @@ func GenerateStrictResponses(t *template.Template, responses []ResponseDefinitio
 	return GenerateTemplates([]string{"strict/strict-responses.tmpl"}, t, responses)
 }
 
-// GenerateClient uses the template engine to generate the function which registers our wrappers
+// Uses the template engine to generate the function which registers our wrappers
 // as Echo path handlers.
 func GenerateClient(t *template.Template, ops []OperationDefinition) (string, error) {
 	return GenerateTemplates([]string{"client.tmpl"}, t, ops)
 }
 
-// GenerateClientWithResponses generates a client which extends the basic client which does response
+// This generates a client which extends the basic client which does response
 // unmarshaling.
 func GenerateClientWithResponses(t *template.Template, ops []OperationDefinition) (string, error) {
 	return GenerateTemplates([]string{"client-with-responses.tmpl"}, t, ops)
diff --git a/pkg/codegen/prune.go b/pkg/codegen/prune.go
index b9f05f5..73f4fb9 100644
--- a/pkg/codegen/prune.go
+++ b/pkg/codegen/prune.go
@@ -394,7 +394,7 @@ func findComponentRefs(swagger *openapi3.T) []string {
 func removeOrphanedComponents(swagger *openapi3.T, refs []string) int {
 	countRemoved := 0
 
-	for key := range swagger.Components.Schemas {
+	for key, _ := range swagger.Components.Schemas {
 		ref := fmt.Sprintf("#/components/schemas/%s", key)
 		if !stringInSlice(ref, refs) {
 			countRemoved++
@@ -402,7 +402,7 @@ func removeOrphanedComponents(swagger *openapi3.T, refs []string) int {
 		}
 	}
 
-	for key := range swagger.Components.Parameters {
+	for key, _ := range swagger.Components.Parameters {
 		ref := fmt.Sprintf("#/components/parameters/%s", key)
 		if !stringInSlice(ref, refs) {
 			countRemoved++
@@ -421,7 +421,7 @@ func removeOrphanedComponents(swagger *openapi3.T, refs []string) int {
 	// 	}
 	// }
 
-	for key := range swagger.Components.RequestBodies {
+	for key, _ := range swagger.Components.RequestBodies {
 		ref := fmt.Sprintf("#/components/requestBodies/%s", key)
 		if !stringInSlice(ref, refs) {
 			countRemoved++
@@ -429,7 +429,7 @@ func removeOrphanedComponents(swagger *openapi3.T, refs []string) int {
 		}
 	}
 
-	for key := range swagger.Components.Responses {
+	for key, _ := range swagger.Components.Responses {
 		ref := fmt.Sprintf("#/components/responses/%s", key)
 		if !stringInSlice(ref, refs) {
 			countRemoved++
@@ -437,7 +437,7 @@ func removeOrphanedComponents(swagger *openapi3.T, refs []string) int {
 		}
 	}
 
-	for key := range swagger.Components.Headers {
+	for key, _ := range swagger.Components.Headers {
 		ref := fmt.Sprintf("#/components/headers/%s", key)
 		if !stringInSlice(ref, refs) {
 			countRemoved++
@@ -445,7 +445,7 @@ func removeOrphanedComponents(swagger *openapi3.T, refs []string) int {
 		}
 	}
 
-	for key := range swagger.Components.Examples {
+	for key, _ := range swagger.Components.Examples {
 		ref := fmt.Sprintf("#/components/examples/%s", key)
 		if !stringInSlice(ref, refs) {
 			countRemoved++
@@ -453,7 +453,7 @@ func removeOrphanedComponents(swagger *openapi3.T, refs []string) int {
 		}
 	}
 
-	for key := range swagger.Components.Links {
+	for key, _ := range swagger.Components.Links {
 		ref := fmt.Sprintf("#/components/links/%s", key)
 		if !stringInSlice(ref, refs) {
 			countRemoved++
@@ -461,7 +461,7 @@ func removeOrphanedComponents(swagger *openapi3.T, refs []string) int {
 		}
 	}
 
-	for key := range swagger.Components.Callbacks {
+	for key, _ := range swagger.Components.Callbacks {
 		ref := fmt.Sprintf("#/components/callbacks/%s", key)
 		if !stringInSlice(ref, refs) {
 			countRemoved++
diff --git a/pkg/codegen/schema.go b/pkg/codegen/schema.go
index 8254cd8..9d83bd5 100644
--- a/pkg/codegen/schema.go
+++ b/pkg/codegen/schema.go
@@ -27,7 +27,7 @@ type Schema struct {
 
 	Description string // The description of the element
 
-	UnionElements []UnionElement // Possible elements of oneOf/anyOf union
+	UnionElements []string       // Possible elements of oneOf/anyOf union
 	Discriminator *Discriminator // Describes which value is stored in a union
 
 	// If this is set, the schema will declare a type via alias, eg,
@@ -146,13 +146,12 @@ type Constants struct {
 //
 // Let's use this example schema:
 // components:
-//
-//	schemas:
-//	  Person:
-//	    type: object
-//	    properties:
-//	    name:
-//	      type: string
+//  schemas:
+//    Person:
+//      type: object
+//      properties:
+//      name:
+//        type: string
 type TypeDefinition struct {
 	// The name of the type, eg, type <...> Person
 	TypeName string
@@ -196,23 +195,6 @@ func (d *Discriminator) PropertyName() string {
 	return SchemaNameToTypeName(d.Property)
 }
 
-// UnionElement describe union element, based on prefix externalRef\d+ and real ref name from external schema.
-type UnionElement string
-
-// String returns externalRef\d+ and real ref name from external schema, like externalRef0.SomeType.
-func (u UnionElement) String() string {
-	return string(u)
-}
-
-// Method generate union method name for template functions `As/From/Merge`.
-func (u UnionElement) Method() string {
-	var method string
-	for _, part := range strings.Split(string(u), `.`) {
-		method += UppercaseFirstCharacter(part)
-	}
-	return method
-}
-
 func PropertiesEqual(a, b Property) bool {
 	return a.JsonFieldName == b.JsonFieldName && a.Schema.TypeDecl() == b.Schema.TypeDecl() && a.Required == b.Required
 }
@@ -577,8 +559,8 @@ type FieldDescriptor struct {
 	IsRef    bool   // Is this schema a reference to predefined object?
 }
 
-// GenFieldsFromProperties produce corresponding field names with JSON annotations,
-// given a list of schema descriptors
+// Given a list of schema descriptors, produce corresponding field names with
+// JSON annotations
 func GenFieldsFromProperties(props []Property) []string {
 	var fields []string
 	for i, p := range props {
@@ -746,7 +728,7 @@ func generateUnion(outSchema *Schema, elements openapi3.SchemaRefs, discriminato
 				}
 			}
 		}
-		outSchema.UnionElements = append(outSchema.UnionElements, UnionElement(elementSchema.GoType))
+		outSchema.UnionElements = append(outSchema.UnionElements, elementSchema.GoType)
 	}
 
 	return nil
diff --git a/pkg/codegen/template_helpers.go b/pkg/codegen/template_helpers.go
index 746c457..a677404 100644
--- a/pkg/codegen/template_helpers.go
+++ b/pkg/codegen/template_helpers.go
@@ -20,7 +20,6 @@ import (
 	"strings"
 	"text/template"
 
-	"github.com/deepmap/oapi-codegen/pkg/util"
 	"github.com/labstack/echo/v4"
 )
 
@@ -30,9 +29,9 @@ const (
 )
 
 var (
-	contentTypesJSON = []string{echo.MIMEApplicationJSON, "text/x-json", "application/problem+json"}
+	contentTypesJSON = []string{echo.MIMEApplicationJSON, "text/x-json"}
 	contentTypesYAML = []string{"application/yaml", "application/x-yaml", "text/yaml", "text/x-yaml"}
-	contentTypesXML  = []string{echo.MIMEApplicationXML, echo.MIMETextXML, "application/problems+xml"}
+	contentTypesXML  = []string{echo.MIMEApplicationXML, echo.MIMETextXML}
 
 	responseTypeSuffix = "Response"
 )
@@ -149,7 +148,7 @@ func genResponseUnmarshal(op *OperationDefinition) string {
 			switch {
 
 			// JSON:
-			case StringInArray(contentTypeName, contentTypesJSON) || util.IsMediaTypeJson(contentTypeName):
+			case StringInArray(contentTypeName, contentTypesJSON):
 				if typeDefinition.ContentTypeName == contentTypeName {
 					caseAction := fmt.Sprintf("var dest %s\n"+
 						"if err := json.Unmarshal(bodyBytes, &dest); err != nil { \n"+
@@ -265,7 +264,7 @@ func stripNewLines(s string) string {
 	return r.Replace(s)
 }
 
-// TemplateFunctions is passed to the template engine, and we can call each
+// This function map is passed to the template engine, and we can call each
 // function here by keyName from the template code.
 var TemplateFunctions = template.FuncMap{
 	"genParamArgs":               genParamArgs,
diff --git a/pkg/codegen/templates/chi/chi-middleware.tmpl b/pkg/codegen/templates/chi/chi-middleware.tmpl
index 77a5c2a..7311ec4 100644
--- a/pkg/codegen/templates/chi/chi-middleware.tmpl
+++ b/pkg/codegen/templates/chi/chi-middleware.tmpl
@@ -177,15 +177,9 @@ func (siw *ServerInterfaceWrapper) {{$opid}}(w http.ResponseWriter, r *http.Requ
     siw.Handler.{{.OperationId}}(w, r{{genParamNames .PathParams}}{{if .RequiresParamObject}}, params{{end}})
   })
 
-  {{if opts.Compatibility.ApplyChiMiddlewareFirstToLast}}
-  for i := len(siw.HandlerMiddlewares) -1; i >= 0; i-- {
-    handler = siw.HandlerMiddlewares[i](handler)
-  }
-  {{else}}
   for _, middleware := range siw.HandlerMiddlewares {
     handler = middleware(handler)
   }
-  {{end}}
 
   handler.ServeHTTP(w, r.WithContext(ctx))
 }
diff --git a/pkg/codegen/templates/imports.tmpl b/pkg/codegen/templates/imports.tmpl
index ef43ef3..376e1f9 100644
--- a/pkg/codegen/templates/imports.tmpl
+++ b/pkg/codegen/templates/imports.tmpl
@@ -27,7 +27,6 @@ import (
 	"github.com/go-chi/chi/v5"
 	"github.com/labstack/echo/v4"
 	"github.com/gin-gonic/gin"
-	"github.com/gorilla/mux"
 	{{- range .ExternalImports}}
 	{{ . }}
 	{{- end}}
diff --git a/pkg/codegen/templates/union.tmpl b/pkg/codegen/templates/union.tmpl
index eb015be..d233e13 100644
--- a/pkg/codegen/templates/union.tmpl
+++ b/pkg/codegen/templates/union.tmpl
@@ -4,15 +4,15 @@
     {{$properties := .Schema.Properties -}}
     {{range .Schema.UnionElements}}
         {{$element := . -}}
-        // As{{ .Method }} returns the union data inside the {{$typeName}} as a {{.}}
-        func (t {{$typeName}}) As{{ .Method }}() ({{.}}, error) {
+        // As{{.}} returns the union data inside the {{$typeName}} as a {{.}}
+        func (t {{$typeName}}) As{{.}}() ({{.}}, error) {
             var body {{.}}
             err := json.Unmarshal(t.union, &body)
             return body, err
         }
 
-        // From{{ .Method }} overwrites any union data inside the {{$typeName}} as the provided {{.}}
-        func (t *{{$typeName}}) From{{ .Method }} (v {{.}}) error {
+        // From{{.}} overwrites any union data inside the {{$typeName}} as the provided {{.}}
+        func (t *{{$typeName}}) From{{.}} (v {{.}}) error {
             {{if $discriminator -}}
                 {{range $value, $type := $discriminator.Mapping -}}
                     {{if eq $type $element -}}
@@ -32,8 +32,8 @@
             return err
         }
 
-        // Merge{{ .Method }} performs a merge with any union data inside the {{$typeName}}, using the provided {{.}}
-        func (t *{{$typeName}}) Merge{{ .Method }} (v {{.}}) error {
+        // Merge{{.}} performs a merge with any union data inside the {{$typeName}}, using the provided {{.}}
+        func (t *{{$typeName}}) Merge{{.}} (v {{.}}) error {
             {{if $discriminator -}}
                 {{range $value, $type := $discriminator.Mapping -}}
                     {{if eq $type $element -}}
diff --git a/pkg/codegen/utils.go b/pkg/codegen/utils.go
index c538f1b..0796b33 100644
--- a/pkg/codegen/utils.go
+++ b/pkg/codegen/utils.go
@@ -93,7 +93,7 @@ func init() {
 	}
 }
 
-// UppercaseFirstCharacter Uppercases the first character in a string. This assumes UTF-8, so we have
+// Uppercase the first character in a string. This assumes UTF-8, so we have
 // to be careful with unicode, don't treat it as a byte array.
 func UppercaseFirstCharacter(str string) string {
 	if str == "" {
@@ -104,8 +104,7 @@ func UppercaseFirstCharacter(str string) string {
 	return string(runes)
 }
 
-// LowercaseFirstCharacter Lowercases the first character in a string. This assumes UTF-8, so we have
-// to be careful with unicode, don't treat it as a byte array.
+// Same as above, except lower case
 func LowercaseFirstCharacter(str string) string {
 	if str == "" {
 		return ""
@@ -115,7 +114,7 @@ func LowercaseFirstCharacter(str string) string {
 	return string(runes)
 }
 
-// ToCamelCase will convert query-arg style strings to CamelCase. We will
+// This function will convert query-arg style strings to CamelCase. We will
 // use `., -, +, :, ;, _, ~, ' ', (, ), {, }, [, ]` as valid delimiters for words.
 // So, "word.word-word+word:word;word_word~word word(word)word{word}[word]"
 // would be converted to WordWordWordWordWordWordWordWordWordWordWordWordWord
@@ -143,7 +142,7 @@ func ToCamelCase(str string) string {
 	return n
 }
 
-// SortedSchemaKeys returns the keys of the given SchemaRef dictionary in sorted
+// This function returns the keys of the given SchemaRef dictionary in sorted
 // order, since Golang scrambles dictionary keys
 func SortedSchemaKeys(dict map[string]*openapi3.SchemaRef) []string {
 	keys := make([]string, len(dict))
@@ -156,7 +155,7 @@ func SortedSchemaKeys(dict map[string]*openapi3.SchemaRef) []string {
 	return keys
 }
 
-// SortedPathsKeys is the same as above, except it sorts the keys for a Paths
+// This function is the same as above, except it sorts the keys for a Paths
 // dictionary.
 func SortedPathsKeys(dict openapi3.Paths) []string {
 	keys := make([]string, len(dict))
@@ -169,7 +168,7 @@ func SortedPathsKeys(dict openapi3.Paths) []string {
 	return keys
 }
 
-// SortedOperationsKeys returns Operation dictionary keys in sorted order
+// This function returns Operation dictionary keys in sorted order
 func SortedOperationsKeys(dict map[string]*openapi3.Operation) []string {
 	keys := make([]string, len(dict))
 	i := 0
@@ -181,7 +180,7 @@ func SortedOperationsKeys(dict map[string]*openapi3.Operation) []string {
 	return keys
 }
 
-// SortedResponsesKeys returns Responses dictionary keys in sorted order
+// This function returns Responses dictionary keys in sorted order
 func SortedResponsesKeys(dict openapi3.Responses) []string {
 	keys := make([]string, len(dict))
 	i := 0
@@ -204,7 +203,7 @@ func SortedHeadersKeys(dict openapi3.Headers) []string {
 	return keys
 }
 
-// SortedContentKeys returns Content dictionary keys in sorted order
+// This returns Content dictionary keys in sorted order
 func SortedContentKeys(dict openapi3.Content) []string {
 	keys := make([]string, len(dict))
 	i := 0
@@ -216,7 +215,7 @@ func SortedContentKeys(dict openapi3.Content) []string {
 	return keys
 }
 
-// SortedStringKeys returns string map keys in sorted order
+// This returns string map keys in sorted order
 func SortedStringKeys(dict map[string]string) []string {
 	keys := make([]string, len(dict))
 	i := 0
@@ -228,7 +227,7 @@ func SortedStringKeys(dict map[string]string) []string {
 	return keys
 }
 
-// SortedParameterKeys returns sorted keys for a ParameterRef dict
+// This returns sorted keys for a ParameterRef dict
 func SortedParameterKeys(dict map[string]*openapi3.ParameterRef) []string {
 	keys := make([]string, len(dict))
 	i := 0
@@ -262,7 +261,7 @@ func SortedSecurityRequirementKeys(sr openapi3.SecurityRequirement) []string {
 	return keys
 }
 
-// StringInArray checks whether the specified string is present in an array
+// This function checks whether the specified string is present in an array
 // of strings
 func StringInArray(str string, array []string) bool {
 	for _, elt := range array {
@@ -331,7 +330,8 @@ func refPathToGoType(refPath string, local bool) (string, error) {
 // #/components/schemas/Foo                     -> true
 // ./local/file.yml#/components/parameters/Bar  -> true
 // ./local/file.yml                             -> false
-// IsGoTypeReference can be used to check whether RefPathToGoType($ref) is possible.
+// The function can be used to check whether RefPathToGoType($ref) is possible.
+//
 func IsGoTypeReference(ref string) bool {
 	return ref != "" && !IsWholeDocumentReference(ref)
 }
@@ -342,91 +342,72 @@ func IsGoTypeReference(ref string) bool {
 // ./local/file.yml                                     -> true
 // http://deepmap.com/schemas/document.json             -> true
 // http://deepmap.com/schemas/document.json#/Foo        -> false
+//
 func IsWholeDocumentReference(ref string) bool {
 	return ref != "" && !strings.ContainsAny(ref, "#")
 }
 
-// SwaggerUriToEchoUri converts a OpenAPI style path URI with parameters to an
+// SwaggerUriToEchoUri converts a OpenAPI style path URI with parameters to a
 // Echo compatible path URI. We need to replace all of OpenAPI parameters with
 // ":param". Valid input parameters are:
-//
-//	{param}
-//	{param*}
-//	{.param}
-//	{.param*}
-//	{;param}
-//	{;param*}
-//	{?param}
-//	{?param*}
+//   {param}
+//   {param*}
+//   {.param}
+//   {.param*}
+//   {;param}
+//   {;param*}
+//   {?param}
+//   {?param*}
 func SwaggerUriToEchoUri(uri string) string {
 	return pathParamRE.ReplaceAllString(uri, ":$1")
 }
 
-// SwaggerUriToFiberUri converts a OpenAPI style path URI with parameters to a
-// Fiber compatible path URI. We need to replace all of OpenAPI parameters with
-// ":param". Valid input parameters are:
-//
-//	{param}
-//	{param*}
-//	{.param}
-//	{.param*}
-//	{;param}
-//	{;param*}
-//	{?param}
-//	{?param*}
-func SwaggerUriToFiberUri(uri string) string {
-	return pathParamRE.ReplaceAllString(uri, ":$1")
-}
-
 // SwaggerUriToChiUri converts a swagger style path URI with parameters to a
-// Chi compatible path URI. We need to replace all Swagger parameters with
+// Chi compatible path URI. We need to replace all of Swagger parameters with
 // "{param}". Valid input parameters are:
-//
-//	{param}
-//	{param*}
-//	{.param}
-//	{.param*}
-//	{;param}
-//	{;param*}
-//	{?param}
-//	{?param*}
+//   {param}
+//   {param*}
+//   {.param}
+//   {.param*}
+//   {;param}
+//   {;param*}
+//   {?param}
+//   {?param*}
 func SwaggerUriToChiUri(uri string) string {
 	return pathParamRE.ReplaceAllString(uri, "{$1}")
 }
 
-// SwaggerUriToGinUri converts a swagger style path URI with parameters to a
-// Gin compatible path URI. We need to replace all Swagger parameters with
+// This function converts a swagger style path URI with parameters to a
+// Gin compatible path URI. We need to replace all of Swagger parameters with
 // ":param". Valid input parameters are:
-//
-//	{param}
-//	{param*}
-//	{.param}
-//	{.param*}
-//	{;param}
-//	{;param*}
-//	{?param}
-//	{?param*}
+//   {param}
+//   {param*}
+//   {.param}
+//   {.param*}
+//   {;param}
+//   {;param*}
+//   {?param}
+//   {?param*}
 func SwaggerUriToGinUri(uri string) string {
 	return pathParamRE.ReplaceAllString(uri, ":$1")
 }
 
-// SwaggerUriToGorillaUri converts a swagger style path URI with parameters to a
-// Gorilla compatible path URI. We need to replace all Swagger parameters with
+// This function converts a swagger style path URI with parameters to a
+// Gorilla compatible path URI. We need to replace all of Swagger parameters with
 // ":param". Valid input parameters are:
-//
-//	{param}
-//	{param*}
-//	{.param}
-//	{.param*}
-//	{;param}
-//	{;param*}
-//	{?param}
-//	{?param*}
+//   {param}
+//   {param*}
+//   {.param}
+//   {.param*}
+//   {;param}
+//   {;param*}
+//   {?param}
+//   {?param*}
 func SwaggerUriToGorillaUri(uri string) string {
 	return pathParamRE.ReplaceAllString(uri, "{$1}")
 }
 
-// OrderedParamsFromUri returns the argument names, in order, in a given URI string, so for
+// Returns the argument names, in order, in a given URI string, so for
 // /path/{param1}/{.param2*}/{?param3}, it would return param1, param2, param3
 func OrderedParamsFromUri(uri string) []string {
 	matches := pathParamRE.FindAllStringSubmatch(uri, -1)
@@ -437,12 +418,12 @@ func OrderedParamsFromUri(uri string) []string {
 	return result
 }
 
-// ReplacePathParamsWithStr replaces path parameters of the form {param} with %s
+// Replaces path parameters of the form {param} with %s
 func ReplacePathParamsWithStr(uri string) string {
 	return pathParamRE.ReplaceAllString(uri, "%s")
 }
 
-// SortParamsByPath reorders the given parameter definitions to match those in the path URI.
+// Reorders the given parameter definitions to match those in the path URI.
 func SortParamsByPath(path string, in []ParameterDefinition) ([]ParameterDefinition, error) {
 	pathParams := OrderedParamsFromUri(path)
 	n := len(in)
@@ -462,7 +443,7 @@ func SortParamsByPath(path string, in []ParameterDefinition) ([]ParameterDefinit
 	return out, nil
 }
 
-// IsGoKeyword returns whether the given string is a go keyword
+// Returns whether the given string is a go keyword
 func IsGoKeyword(str string) bool {
 	return token.IsKeyword(str)
 }
@@ -633,7 +614,7 @@ func SchemaHasAdditionalProperties(schema *openapi3.Schema) bool {
 	return false
 }
 
-// PathToTypeName converts a path, like Object/field1/nestedField into a go
+// This converts a path, like Object/field1/nestedField into a go
 // type name.
 func PathToTypeName(path []string) string {
 	for i, p := range path {
@@ -681,7 +662,7 @@ func stringToGoCommentWithPrefix(in, prefix string) string {
 	return in
 }
 
-// EscapePathElements breaks apart a path, and looks at each element. If it's
+// This function breaks apart a path, and looks at each element. If it's
 // not a path parameter, eg, {param}, it will URL-escape the element.
 func EscapePathElements(path string) string {
 	elems := strings.Split(path, "/")
@@ -810,26 +791,27 @@ func findSchemaNameByRefPath(refPath string, spec *openapi3.T) (string, error) {
 	return "", nil
 }
 
-func ParseGoImportExtension(v *openapi3.SchemaRef) (*goImport, error) {
-	if v.Value.Extensions[extPropGoImport] == nil || v.Value.Extensions[extPropGoType] == nil {
-		return nil, nil
-	}
-
-	goTypeImportExt := v.Value.Extensions[extPropGoImport]
-
-	if raw, ok := goTypeImportExt.(json.RawMessage); ok {
-		gi := goImport{}
-		if err := json.Unmarshal(raw, &gi); err != nil {
-			return nil, err
+func GetImports(dict map[string]*openapi3.SchemaRef) (map[string]goImport, error) {
+	res := map[string]goImport{}
+	for _, v := range dict {
+		if v == nil || v.Value == nil {
+			continue
 		}
-		return &gi, nil
-	}
 
-	return nil, nil
-}
+		if v.Value.Extensions["x-go-type-import"] == nil || v.Value.Extensions["x-go-type"] == nil {
+			continue
+		}
+		goTypeImportExt := v.Value.Extensions["x-go-type-import"]
 
-func MergeImports(dst, src map[string]goImport) {
-	for k, v := range src {
-		dst[k] = v
+		if raw, ok := goTypeImportExt.(json.RawMessage); ok {
+			gi := goImport{}
+			if err := json.Unmarshal(raw, &gi); err != nil {
+				return nil, err
+			}
+			res[gi.String()] = gi
+		} else {
+			continue
+		}
 	}
+	return res, nil
 }
diff --git a/pkg/gin-middleware/oapi_validate.go b/pkg/gin-middleware/oapi_validate.go
index e2097b6..6070195 100644
--- a/pkg/gin-middleware/oapi_validate.go
+++ b/pkg/gin-middleware/oapi_validate.go
@@ -18,8 +18,8 @@ import (
 	"context"
 	"errors"
 	"fmt"
-	"net/http"
 	"os"
+	"net/http"
 	"strings"
 
 	"github.com/getkin/kin-openapi/openapi3"
@@ -34,7 +34,7 @@ const (
 	UserDataKey   = "oapi-codegen/user-data"
 )
 
-// OapiValidatorFromYamlFile creates a validator middleware from a YAML file path
+// Create validator middleware from a YAML file path
 func OapiValidatorFromYamlFile(path string) (gin.HandlerFunc, error) {
 	data, err := os.ReadFile(path)
 	if err != nil {
@@ -49,7 +49,7 @@ func OapiValidatorFromYamlFile(path string) (gin.HandlerFunc, error) {
 	return OapiRequestValidator(swagger), nil
 }
 
-// OapiRequestValidator is an gin middleware function which validates incoming HTTP requests
+// This is an gin middleware function which validates incoming HTTP requests
 // to make sure that they conform to the given OAPI 3.0 specification. When
 // OAPI validation fails on the request, we return an HTTP/400 with error message
 func OapiRequestValidator(swagger *openapi3.T) gin.HandlerFunc {
@@ -72,7 +72,7 @@ type Options struct {
 	MultiErrorHandler MultiErrorHandler
 }
 
-// OapiRequestValidatorWithOptions creates a validator from a swagger object, with validation options
+// Create a validator from a swagger object, with validation options
 func OapiRequestValidatorWithOptions(swagger *openapi3.T, options *Options) gin.HandlerFunc {
 	router, err := gorillamux.NewRouter(swagger)
 	if err != nil {
@@ -156,7 +156,7 @@ func ValidateRequestFromContext(c *gin.Context, router routers.Router, options *
 	return nil
 }
 
-// GetGinContext gets the echo context from within requests. It returns
+// Helper function to get the echo context from within requests. It returns
 // nil if not found or wrong type.
 func GetGinContext(c context.Context) *gin.Context {
 	iface := c.Value(GinContextKey)
diff --git a/pkg/middleware/oapi_validate.go b/pkg/middleware/oapi_validate.go
index 6a48a49..c381d39 100644
--- a/pkg/middleware/oapi_validate.go
+++ b/pkg/middleware/oapi_validate.go
@@ -18,8 +18,8 @@ import (
 	"context"
 	"errors"
 	"fmt"
-	"net/http"
 	"os"
+	"net/http"
 	"strings"
 
 	"github.com/getkin/kin-openapi/openapi3"
@@ -35,9 +35,10 @@ const (
 	UserDataKey    = "oapi-codegen/user-data"
 )
 
-// OapiValidatorFromYamlFile is an Echo middleware function which validates incoming HTTP requests
+// This is an Echo middleware function which validates incoming HTTP requests
 // to make sure that they conform to the given OAPI 3.0 specification. When
 // OAPI validation fails on the request, we return an HTTP/400.
+
 // Create validator middleware from a YAML file path
 func OapiValidatorFromYamlFile(path string) (echo.MiddlewareFunc, error) {
 	data, err := os.ReadFile(path)
@@ -53,7 +54,7 @@ func OapiValidatorFromYamlFile(path string) (echo.MiddlewareFunc, error) {
 	return OapiRequestValidator(swagger), nil
 }
 
-// OapiRequestValidator creates a validator from a swagger object.
+// Create a validator from a swagger object.
 func OapiRequestValidator(swagger *openapi3.T) echo.MiddlewareFunc {
 	return OapiRequestValidatorWithOptions(swagger, nil)
 }
@@ -182,7 +183,7 @@ func ValidateRequestFromContext(ctx echo.Context, router routers.Router, options
 	return nil
 }
 
-// GetEchoContext gets the echo context from within requests. It returns
+// Helper function to get the echo context from within requests. It returns
 // nil if not found or wrong type.
 func GetEchoContext(c context.Context) echo.Context {
 	iface := c.Value(EchoContextKey)
diff --git a/pkg/runtime/bind.go b/pkg/runtime/bind.go
index 1551250..3e2a689 100644
--- a/pkg/runtime/bind.go
+++ b/pkg/runtime/bind.go
@@ -21,4 +21,4 @@ package runtime
 // Binder implements Bind("") as a no-op.
 type Binder interface {
 	Bind(src string) error
-}
+}
\ No newline at end of file
diff --git a/pkg/runtime/bindparam.go b/pkg/runtime/bindparam.go
index 13d8706..33d51de 100644
--- a/pkg/runtime/bindparam.go
+++ b/pkg/runtime/bindparam.go
@@ -26,7 +26,7 @@ import (
 	"github.com/deepmap/oapi-codegen/pkg/types"
 )
 
-// BindStyledParameter binds a parameter as described in the Path Parameters
+// This function binds a parameter as described in the Path Parameters
 // section here to a Go object:
 // https://swagger.io/docs/specification/serialization/
 // It is a backward compatible function to clients generated with codegen
@@ -36,7 +36,7 @@ func BindStyledParameter(style string, explode bool, paramName string,
 	return BindStyledParameterWithLocation(style, explode, paramName, ParamLocationUndefined, value, dest)
 }
 
-// BindStyledParameterWithLocation binds a parameter as described in the Path Parameters
+// This function binds a parameter as described in the Path Parameters
 // section here to a Go object:
 // https://swagger.io/docs/specification/serialization/
 func BindStyledParameterWithLocation(style string, explode bool, paramName string,
diff --git a/pkg/runtime/bindstring.go b/pkg/runtime/bindstring.go
index e106b5a..f597dab 100644
--- a/pkg/runtime/bindstring.go
+++ b/pkg/runtime/bindstring.go
@@ -24,7 +24,7 @@ import (
 	"github.com/deepmap/oapi-codegen/pkg/types"
 )
 
-// BindStringToObject takes a string, and attempts to assign it to the destination
+// This function takes a string, and attempts to assign it to the destination
 // interface via whatever type conversion is necessary. We have to do this
 // via reflection instead of a much simpler type switch so that we can handle
 // type aliases. This function was the easy way out, the better way, since we
diff --git a/pkg/runtime/styleparam.go b/pkg/runtime/styleparam.go
index 2ba86d9..6de67cf 100644
--- a/pkg/runtime/styleparam.go
+++ b/pkg/runtime/styleparam.go
@@ -28,7 +28,6 @@ import (
 )
 
 // Parameter escaping works differently based on where a header is found
-
 type ParamLocation int
 
 const (
@@ -39,7 +38,7 @@ const (
 	ParamLocationCookie
 )
 
-// StyleParam is used by older generated code, and must remain compatible
+// This function is used by older generated code, and must remain compatible
 // with that code. It is not to be used in new templates. Please see the
 // function below, which can specialize its output based on the location of
 // the parameter.
diff --git a/tools/tools.go b/tools/tools.go
index f3c3d2f..bbb857f 100644
--- a/tools/tools.go
+++ b/tools/tools.go
@@ -3,5 +3,6 @@
 package tools
 
 import (
+	_ "github.com/cyberdelia/templates"
 	_ "github.com/matryer/moq"
 )


Test patch:
diff --git a/examples/authenticated-api/echo/server/server_test.go b/examples/authenticated-api/echo/server/server_test.go
index 21366f5..4c7ba4c 100644
--- a/examples/authenticated-api/echo/server/server_test.go
+++ b/examples/authenticated-api/echo/server/server_test.go
@@ -55,7 +55,7 @@ func TestAPI(t *testing.T) {
 	jwts := []string{string(readerJWT), string(writerJWT)}
 	for _, jwt := range jwts {
 		response := testutil.NewRequest().Get("/things").
-			WithJWSAuth(jwt).
+			WithJWSAuth(string(jwt)).
 			WithAcceptJson().Go(t, e)
 		assert.Equal(t, http.StatusOK, response.Code())
 	}
diff --git a/examples/petstore-expanded/chi/petstore_test.go b/examples/petstore-expanded/chi/petstore_test.go
index 5e36439..b12c4ce 100644
--- a/examples/petstore-expanded/chi/petstore_test.go
+++ b/examples/petstore-expanded/chi/petstore_test.go
@@ -7,12 +7,13 @@ import (
 	"net/http/httptest"
 	"testing"
 
-	"github.com/deepmap/oapi-codegen/examples/petstore-expanded/chi/api"
-	middleware "github.com/deepmap/oapi-codegen/pkg/chi-middleware"
-	"github.com/deepmap/oapi-codegen/pkg/testutil"
 	"github.com/go-chi/chi/v5"
 	"github.com/stretchr/testify/assert"
 	"github.com/stretchr/testify/require"
+
+	"github.com/deepmap/oapi-codegen/examples/petstore-expanded/chi/api"
+	middleware "github.com/deepmap/oapi-codegen/pkg/chi-middleware"
+	"github.com/deepmap/oapi-codegen/pkg/testutil"
 )
 
 func doGet(t *testing.T, mux *chi.Mux, url string) *httptest.ResponseRecorder {
@@ -84,8 +85,8 @@ func TestPetStore(t *testing.T) {
 
 	t.Run("List all pets", func(t *testing.T) {
 		store.Pets = map[int64]api.Pet{
-			1: {},
-			2: {},
+			1: api.Pet{},
+			2: api.Pet{},
 		}
 
 		// Now, list all pets, we should have two
@@ -120,11 +121,11 @@ func TestPetStore(t *testing.T) {
 
 	t.Run("Filter pets by tag", func(t *testing.T) {
 		store.Pets = map[int64]api.Pet{
-			1: {},
-			2: {},
+			1: api.Pet{},
+			2: api.Pet{},
 		}
 
-		// Filter pets by non-existent tag, we should have 0
+		// Filter pets by non existent tag, we should have 0
 		rr := doGet(t, r, "/pets?tags=NotExists")
 		assert.Equal(t, http.StatusOK, rr.Code)
 
@@ -136,8 +137,8 @@ func TestPetStore(t *testing.T) {
 
 	t.Run("Delete pets", func(t *testing.T) {
 		store.Pets = map[int64]api.Pet{
-			1: {},
-			2: {},
+			1: api.Pet{},
+			2: api.Pet{},
 		}
 
 		// Let's delete non-existent pet
diff --git a/examples/petstore-expanded/echo/petstore_test.go b/examples/petstore-expanded/echo/petstore_test.go
index 36f5f42..00d1bf9 100644
--- a/examples/petstore-expanded/echo/petstore_test.go
+++ b/examples/petstore-expanded/echo/petstore_test.go
@@ -19,14 +19,15 @@ import (
 	"net/http"
 	"testing"
 
+	"github.com/labstack/echo/v4"
+	echo_middleware "github.com/labstack/echo/v4/middleware"
+	"github.com/stretchr/testify/assert"
+	"github.com/stretchr/testify/require"
+
 	"github.com/deepmap/oapi-codegen/examples/petstore-expanded/echo/api"
 	"github.com/deepmap/oapi-codegen/examples/petstore-expanded/echo/api/models"
 	"github.com/deepmap/oapi-codegen/pkg/middleware"
 	"github.com/deepmap/oapi-codegen/pkg/testutil"
-	"github.com/labstack/echo/v4"
-	echoMiddleware "github.com/labstack/echo/v4/middleware"
-	"github.com/stretchr/testify/assert"
-	"github.com/stretchr/testify/require"
 )
 
 func TestPetStore(t *testing.T) {
@@ -49,7 +50,7 @@ func TestPetStore(t *testing.T) {
 	e.Use(middleware.OapiRequestValidator(swagger))
 
 	// Log requests
-	e.Use(echoMiddleware.Logger())
+	e.Use(echo_middleware.Logger())
 
 	// We register the autogenerated boilerplate and bind our PetStore to this
 	// echo router.
diff --git a/examples/petstore-expanded/gin/petstore_test.go b/examples/petstore-expanded/gin/petstore_test.go
index ccb38de..71bee77 100644
--- a/examples/petstore-expanded/gin/petstore_test.go
+++ b/examples/petstore-expanded/gin/petstore_test.go
@@ -7,9 +7,10 @@ import (
 	"net/http/httptest"
 	"testing"
 
+	"github.com/stretchr/testify/assert"
+
 	"github.com/deepmap/oapi-codegen/examples/petstore-expanded/gin/api"
 	"github.com/deepmap/oapi-codegen/pkg/testutil"
-	"github.com/stretchr/testify/assert"
 )
 
 func doGet(t *testing.T, handler http.Handler, url string) *httptest.ResponseRecorder {
diff --git a/examples/petstore-expanded/gorilla/petstore_test.go b/examples/petstore-expanded/gorilla/petstore_test.go
index c60afbc..c325326 100644
--- a/examples/petstore-expanded/gorilla/petstore_test.go
+++ b/examples/petstore-expanded/gorilla/petstore_test.go
@@ -7,12 +7,13 @@ import (
 	"net/http/httptest"
 	"testing"
 
-	"github.com/deepmap/oapi-codegen/examples/petstore-expanded/gorilla/api"
-	middleware "github.com/deepmap/oapi-codegen/pkg/chi-middleware"
-	"github.com/deepmap/oapi-codegen/pkg/testutil"
 	"github.com/gorilla/mux"
 	"github.com/stretchr/testify/assert"
 	"github.com/stretchr/testify/require"
+
+	"github.com/deepmap/oapi-codegen/examples/petstore-expanded/gorilla/api"
+	middleware "github.com/deepmap/oapi-codegen/pkg/chi-middleware"
+	"github.com/deepmap/oapi-codegen/pkg/testutil"
 )
 
 func doGet(t *testing.T, mux *mux.Router, url string) *httptest.ResponseRecorder {
@@ -84,8 +85,8 @@ func TestPetStore(t *testing.T) {
 
 	t.Run("List all pets", func(t *testing.T) {
 		store.Pets = map[int64]api.Pet{
-			1: {},
-			2: {},
+			1: api.Pet{},
+			2: api.Pet{},
 		}
 
 		// Now, list all pets, we should have two
@@ -120,8 +121,8 @@ func TestPetStore(t *testing.T) {
 
 	t.Run("Filter pets by tag", func(t *testing.T) {
 		store.Pets = map[int64]api.Pet{
-			1: {},
-			2: {},
+			1: api.Pet{},
+			2: api.Pet{},
 		}
 
 		// Filter pets by non existent tag, we should have 0
@@ -136,8 +137,8 @@ func TestPetStore(t *testing.T) {
 
 	t.Run("Delete pets", func(t *testing.T) {
 		store.Pets = map[int64]api.Pet{
-			1: {},
-			2: {},
+			1: api.Pet{},
+			2: api.Pet{},
 		}
 
 		// Let's delete non-existent pet
diff --git a/examples/petstore-expanded/strict/petstore_test.go b/examples/petstore-expanded/strict/petstore_test.go
index 34891e0..67bbb1a 100644
--- a/examples/petstore-expanded/strict/petstore_test.go
+++ b/examples/petstore-expanded/strict/petstore_test.go
@@ -7,12 +7,13 @@ import (
 	"net/http/httptest"
 	"testing"
 
-	"github.com/deepmap/oapi-codegen/examples/petstore-expanded/strict/api"
-	middleware "github.com/deepmap/oapi-codegen/pkg/chi-middleware"
-	"github.com/deepmap/oapi-codegen/pkg/testutil"
 	"github.com/go-chi/chi/v5"
 	"github.com/stretchr/testify/assert"
 	"github.com/stretchr/testify/require"
+
+	"github.com/deepmap/oapi-codegen/examples/petstore-expanded/strict/api"
+	middleware "github.com/deepmap/oapi-codegen/pkg/chi-middleware"
+	"github.com/deepmap/oapi-codegen/pkg/testutil"
 )
 
 func doGet(t *testing.T, mux *chi.Mux, url string) *httptest.ResponseRecorder {
@@ -84,8 +85,8 @@ func TestPetStore(t *testing.T) {
 
 	t.Run("List all pets", func(t *testing.T) {
 		store.Pets = map[int64]api.Pet{
-			1: {},
-			2: {},
+			1: api.Pet{},
+			2: api.Pet{},
 		}
 
 		// Now, list all pets, we should have two
@@ -120,11 +121,11 @@ func TestPetStore(t *testing.T) {
 
 	t.Run("Filter pets by tag", func(t *testing.T) {
 		store.Pets = map[int64]api.Pet{
-			1: {},
-			2: {},
+			1: api.Pet{},
+			2: api.Pet{},
 		}
 
-		// Filter pets by non-existent tag, we should have 0
+		// Filter pets by non existent tag, we should have 0
 		rr := doGet(t, r, "/pets?tags=NotExists")
 		assert.Equal(t, http.StatusOK, rr.Code)
 
@@ -136,8 +137,8 @@ func TestPetStore(t *testing.T) {
 
 	t.Run("Delete pets", func(t *testing.T) {
 		store.Pets = map[int64]api.Pet{
-			1: {},
-			2: {},
+			1: api.Pet{},
+			2: api.Pet{},
 		}
 
 		// Let's delete non-existent pet
diff --git a/internal/test/all_of/openapi.yaml b/internal/test/all_of/openapi.yaml
index f73a8e5..e405c53 100644
--- a/internal/test/all_of/openapi.yaml
+++ b/internal/test/all_of/openapi.yaml
@@ -38,7 +38,7 @@ components:
         properties with another Schema which only provides required fields.
       allOf:
         - $ref: "#/components/schemas/PersonProperties"
-        - required: [ FirstName, LastName ]
+        - required: [FirstName, LastName]
     PersonWithID:
       type: object
       description: |
diff --git a/internal/test/client/client.yaml b/internal/test/client/client.yaml
index ea4c1c3..3517933 100644
--- a/internal/test/client/client.yaml
+++ b/internal/test/client/client.yaml
@@ -11,7 +11,7 @@ paths:
     get:
       operationId: GetJson
       security:
-        - OpenId: [ json.read, json.admin ]
+      - OpenId: [json.read, json.admin]
       responses:
         200:
           application/json:
@@ -21,7 +21,7 @@ paths:
     get:
       operationId: GetJsonWithTrailingSlash
       security:
-        - OpenId: [ json.read, json.admin ]
+        - OpenId: [json.read, json.admin]
       responses:
         200:
           application/json:
diff --git a/internal/test/client/client_test.go b/internal/test/client/client_test.go
index da499f5..62e132a 100644
--- a/internal/test/client/client_test.go
+++ b/internal/test/client/client_test.go
@@ -9,8 +9,8 @@ import (
 func TestTemp(t *testing.T) {
 
 	var (
-		withTrailingSlash    = "https://my-api.com/some-base-url/v1/"
-		withoutTrailingSlash = "https://my-api.com/some-base-url/v1"
+		withTrailingSlash    string = "https://my-api.com/some-base-url/v1/"
+		withoutTrailingSlash string = "https://my-api.com/some-base-url/v1"
 	)
 
 	client1, err := NewClient(
diff --git a/internal/test/components/components.yaml b/internal/test/components/components.yaml
index 4bc4fe7..f49173a 100644
--- a/internal/test/components/components.yaml
+++ b/internal/test/components/components.yaml
@@ -11,9 +11,9 @@ paths:
       description: |
         This endpoint exists so that components can be created in this
         spec and not be pruned
-      # TODO: figure out why uncommenting this causes failures
-      #   parameters:
-      #     - $ref: "#/components/parameters/ParameterObject"
+    # TODO: figure out why uncommenting this causes failures
+    #   parameters:
+    #     - $ref: "#/components/parameters/ParameterObject"
       requestBody:
         $ref: "#/components/requestBodies/RequestBody"
       responses:
@@ -93,7 +93,7 @@ paths:
                 type: object
                 additionalProperties:
                   type: string
-            required: [ inner ]
+            required: [inner]
       responses:
         default:
           description: placeholder
@@ -118,7 +118,7 @@ paths:
                   type: object
                   additionalProperties:
                     type: integer
-              required: [ name, inner ]
+              required: [name, inner]
               additionalProperties: true
       responses:
         default:
@@ -159,7 +159,7 @@ components:
           type: integer
         optional:
           type: string
-      required: [ name, id ]
+      required: [name, id]
       additionalProperties:
         type: integer
     AdditionalPropertiesObject2:
@@ -170,7 +170,7 @@ components:
           type: string
         id:
           type: integer
-      required: [ name, id ]
+      required: [name, id]
       additionalProperties: false
     AdditionalPropertiesObject3:
       description: Allows any additional property
@@ -178,7 +178,7 @@ components:
       properties:
         name:
           type: string
-      required: [ name ]
+      required: [name]
       additionalProperties: true
     AdditionalPropertiesObject4:
       description: Has anonymous field which has additional properties
@@ -191,9 +191,9 @@ components:
           properties:
             name:
               type: string
-          required: [ name ]
+          required: [name]
           additionalProperties: true
-      required: [ inner, name ]
+      required: [inner, name]
       additionalProperties: true
     AdditionalPropertiesObject5:
       description: Has additional properties with schema for dictionaries
@@ -381,13 +381,13 @@ components:
         value2:
           type: string
           format: json
-      required: [ name, value1 ]
+      required: [name, value1]
     Enum1:
       description: |
         Conflicts with Enum2, enum values need to be prefixed with type
         name.
       type: string
-      enum: [ One, Two, Three ]
+      enum: [One, Two, Three]
     Enum2:
       description: |
         Conflicts with Enum1, enum values need to be prefixed with type
@@ -420,8 +420,8 @@ components:
       description: |
         Two enums of the same type combined with allOf.
       allOf:
-        - $ref: "#/components/schemas/Enum1"
-        - enum: [ Seven ]
+      - $ref: "#/components/schemas/Enum1"
+      - enum: [ Seven ]
     FunnyValues:
       description: Edge cases for enum names
       type: string
@@ -440,14 +440,14 @@ components:
           type: string
         prop2:
           type: string
-      required: [ prop1, prop2 ]
+      required: [prop1, prop2]
     ReferenceToRenameMe:
       description: When a Schema is renamed, $ref should refer to the new name
       type: object
       properties:
         ToNewName:
           $ref: "#/components/schemas/RenameMe"
-      required: [ ToNewName ]
+      required: [ToNewName]
   responses:
     ResponseObject:
       x-go-name: RenamedResponseObject
@@ -484,7 +484,7 @@ components:
       in: query
       schema:
         type: string
-        enum: [ on, off, both ]
+        enum: [on, off, both]
     EnumParam2:
       name: ParamEnum2
       description: a parameter
diff --git a/internal/test/externalref/externalref.gen.go b/internal/test/externalref/externalref.gen.go
index 698bc3f..b9b62d1 100644
--- a/internal/test/externalref/externalref.gen.go
+++ b/internal/test/externalref/externalref.gen.go
@@ -19,16 +19,18 @@ import (
 
 // Container defines model for Container.
 type Container struct {
-	ObjectA *externalRef0.ObjectA `json:"object_a,omitempty"`
-	ObjectB *externalRef1.ObjectB `json:"object_b,omitempty"`
+	ObjectA *externalRef0.ObjectA   `json:"object_a,omitempty"`
+	ObjectB *externalRef1.ObjectB   `json:"object_b,omitempty"`
+	ObjectC *map[string]interface{} `json:"object_c,omitempty"`
 }
 
 // Base64 encoded, gzipped, json marshaled Swagger object
 var swaggerSpec = []string{
 
-	"H4sIAAAAAAAC/4zPQcrCMBAF4Lu8/1+GpOAuu9YDeASZhqmNtsmQBEFK7i4pihsXZvUeYb5hNri4Sgwc",
-	"SobdkN3MK+3xGEMhHzi1IikKp+J5/4rjlV05U8v/iSdYaCPkbnTh3mRhpx+0Ln/mg5uXbE77bI+q3sz4",
-	"jRl+YgbU9hR8mGJjii8LwwIKd07Zx9BK2yUcSDwsDrrTHRSEytyuqfUZAAD//0P8tE0FAQAA",
+	"H4sIAAAAAAAC/5yPQU7EMAxF72JYRtOR2GXHcAC4AfJkPNSotaPEIKEqd0dJKa1gQcUqtvzf/z8TBB2j",
+	"Coll8BPk0NOIbXxQMWShVJeYNFIypnbS8ysFe8Y63ya6goebbjXqvly6x6a7h+IW5LwPOW2Q8BfyrSul",
+	"OFgyf5UWHKm+9hEJPGRLLC//qrbGnHbHlB8fwsuFjVVweNrglt7ILegsn1GWqzZXtqHewME7pcwqdane",
+	"kQQjg4e7w/FwBAcRra+NSvkMAAD//3vXjDblAQAA",
 }
 
 // GetSwagger returns the content of the embedded swagger specification file
diff --git a/internal/test/externalref/imports_test.go b/internal/test/externalref/imports_test.go
index c3e326f..0ca9e39 100644
--- a/internal/test/externalref/imports_test.go
+++ b/internal/test/externalref/imports_test.go
@@ -3,9 +3,10 @@ package externalref
 import (
 	"testing"
 
+	"github.com/stretchr/testify/require"
+
 	"github.com/deepmap/oapi-codegen/internal/test/externalref/packageA"
 	"github.com/deepmap/oapi-codegen/internal/test/externalref/packageB"
-	"github.com/stretchr/testify/require"
 )
 
 func TestParameters(t *testing.T) {
@@ -25,4 +26,4 @@ func TestGetSwagger(t *testing.T) {
 
 	_, err = GetSwagger()
 	require.Nil(t, err)
-}
+}
\ No newline at end of file
diff --git a/internal/test/externalref/object_c.json b/internal/test/externalref/object_c.json
new file mode 100644
index 0000000..b85043d
--- /dev/null
+++ b/internal/test/externalref/object_c.json
@@ -0,0 +1,5 @@
+{
+  "type": "object",
+  "properties": {},
+  "additionalProperties": true
+}
diff --git a/internal/test/externalref/packageA/externalref.gen.go b/internal/test/externalref/packageA/externalref.gen.go
index 3b58e3c..01505b1 100644
--- a/internal/test/externalref/packageA/externalref.gen.go
+++ b/internal/test/externalref/packageA/externalref.gen.go
@@ -25,9 +25,9 @@ type ObjectA struct {
 // Base64 encoded, gzipped, json marshaled Swagger object
 var swaggerSpec = []string{
 
-	"H4sIAAAAAAAC/0SNQarDMAwF7/L+X5p4711zgR6hKEZJ3MaysN1FCLl7sVOoNhoYHnPAp6hJWGqBO1D8",
-	"ypE63qcn+3prqDkp5xq4C6HI7dddGQ6l5iALToPUF4+pyf/MMxyGwSr5Fy082qLsh53i9md/Ufst2is3",
-	"4mxnEGROcPLeNoOkLKQBDjBQqmu5zPkJAAD//0utOZO+AAAA",
+	"H4sIAAAAAAAC/4yNQa7CMAxE7zL/LyN1nx1cgCOgtHJpUGtbiVmgyndHSUFsWXmsp3mzY5JNhYmtIu6o",
+	"00Jb6vEy3mmyU4taRKlYpg44bdSuPZUQUa1kvsEDpDeuY4P/hWZE/A1f//CWD4f5DHcP+Dy/znhvZZ4F",
+	"kR/rGiBKnDQjAgGabKkH8VcAAAD//0SMp77dAAAA",
 }
 
 // GetSwagger returns the content of the embedded swagger specification file
diff --git a/internal/test/externalref/spec.yaml b/internal/test/externalref/spec.yaml
index 3f42c7d..41187ab 100644
--- a/internal/test/externalref/spec.yaml
+++ b/internal/test/externalref/spec.yaml
@@ -1,6 +1,6 @@
 openapi: "3.0.0"
-info: { }
-paths: { }
+info: {}
+paths: {}
 components:
   schemas:
     Container:
@@ -9,3 +9,5 @@ components:
           $ref: ./packageA/spec.yaml#/components/schemas/ObjectA
         object_b:
           $ref: ./packageB/spec.yaml#/components/schemas/ObjectB
+        object_c:
+          $ref: ./object_c.json
diff --git a/internal/test/issues/issue-312/spec.yaml b/internal/test/issues/issue-312/spec.yaml
index f7f2027..47be65f 100644
--- a/internal/test/issues/issue-312/spec.yaml
+++ b/internal/test/issues/issue-312/spec.yaml
@@ -35,11 +35,11 @@ paths:
       summary: Get pet given identifier.
       operationId: getPet
       parameters:
-        - name: petId
-          in: path
-          required: true
-          schema:
-            type: string
+      - name: petId
+        in: path
+        required: true
+        schema:
+          type: string
       responses:
         '200':
           description: valid pet
diff --git a/internal/test/issues/issue-52/issue_test.go b/internal/test/issues/issue-52/issue_test.go
index 12edb76..960c266 100644
--- a/internal/test/issues/issue-52/issue_test.go
+++ b/internal/test/issues/issue-52/issue_test.go
@@ -4,9 +4,10 @@ import (
 	_ "embed"
 	"testing"
 
-	"github.com/deepmap/oapi-codegen/pkg/codegen"
 	"github.com/getkin/kin-openapi/openapi3"
 	"github.com/stretchr/testify/require"
+
+	"github.com/deepmap/oapi-codegen/pkg/codegen"
 )
 
 //go:embed spec.yaml
diff --git a/internal/test/issues/issue-grab_import_names/issue_test.go b/internal/test/issues/issue-grab_import_names/issue_test.go
index c00b42d..1f90f83 100644
--- a/internal/test/issues/issue-grab_import_names/issue_test.go
+++ b/internal/test/issues/issue-grab_import_names/issue_test.go
@@ -3,9 +3,10 @@ package grab_import_names
 import (
 	"testing"
 
-	"github.com/deepmap/oapi-codegen/pkg/codegen"
 	"github.com/getkin/kin-openapi/openapi3"
 	"github.com/stretchr/testify/require"
+
+	"github.com/deepmap/oapi-codegen/pkg/codegen"
 )
 
 func TestLineComments(t *testing.T) {
diff --git a/internal/test/issues/issue-illegal_enum_names/issue_test.go b/internal/test/issues/issue-illegal_enum_names/issue_test.go
index 4d7c2c8..c924eaa 100644
--- a/internal/test/issues/issue-illegal_enum_names/issue_test.go
+++ b/internal/test/issues/issue-illegal_enum_names/issue_test.go
@@ -6,9 +6,10 @@ import (
 	"go/token"
 	"testing"
 
-	"github.com/deepmap/oapi-codegen/pkg/codegen"
 	"github.com/getkin/kin-openapi/openapi3"
 	"github.com/stretchr/testify/require"
+
+	"github.com/deepmap/oapi-codegen/pkg/codegen"
 )
 
 func TestIllegalEnumNames(t *testing.T) {
diff --git a/internal/test/parameters/parameters.yaml b/internal/test/parameters/parameters.yaml
index 682af6a..2790b6c 100644
--- a/internal/test/parameters/parameters.yaml
+++ b/internal/test/parameters/parameters.yaml
@@ -25,16 +25,16 @@ paths:
     get:
       operationId: getSimpleNoExplodeArray
       parameters:
-        - name: param
-          in: path
-          required: true
-          style: simple
-          explode: false
-          schema:
-            type: array
-            items:
-              type: integer
-              format: int32
+      - name: param
+        in: path
+        required: true
+        style: simple
+        explode: false
+        schema:
+          type: array
+          items:
+            type: integer
+            format: int32
       responses:
         '200':
           $ref: "#/components/responses/SimpleResponse"
@@ -342,7 +342,7 @@ paths:
             $ref: "#/components/schemas/ComplexObject"
       responses:
         default:
-          $ref: "#/components/responses/SimpleResponse"
+         $ref: "#/components/responses/SimpleResponse"
   /header:
     get:
       operationId: getHeader
@@ -490,14 +490,14 @@ paths:
     get:
       operationId: enumParams
       parameters:
-        - name: enumPathParam
-          description: Parameter with enum values
-          in: query
-          required: false
-          schema:
-            type: integer
-            format: int32
-            enum: [ 100, 200 ]
+       - name: enumPathParam
+         description: Parameter with enum values
+         in: query
+         required: false
+         schema:
+           type: integer
+           format: int32
+           enum: [100, 200]
       responses:
         204:
           description: no content
diff --git a/internal/test/parameters/parameters_test.go b/internal/test/parameters/parameters_test.go
index 3e3fb54..b0fe6b1 100644
--- a/internal/test/parameters/parameters_test.go
+++ b/internal/test/parameters/parameters_test.go
@@ -7,11 +7,12 @@ import (
 	"net/http/httptest"
 	"testing"
 
-	"github.com/deepmap/oapi-codegen/pkg/testutil"
 	"github.com/labstack/echo/v4"
 	"github.com/labstack/echo/v4/middleware"
 	"github.com/stretchr/testify/assert"
 	"github.com/stretchr/testify/require"
+
+	"github.com/deepmap/oapi-codegen/pkg/testutil"
 )
 
 type testServer struct {
@@ -40,91 +41,91 @@ func (t *testServer) reset() {
 	t.headerParams = nil
 }
 
-// (GET /contentObject/{param})
+//  (GET /contentObject/{param})
 func (t *testServer) GetContentObject(ctx echo.Context, param ComplexObject) error {
 	t.complexObject = &param
 	return nil
 }
 
-// (GET /labelExplodeArray/{.param*})
+//  (GET /labelExplodeArray/{.param*})
 func (t *testServer) GetLabelExplodeArray(ctx echo.Context, param []int32) error {
 	t.array = param
 	return nil
 }
 
-// (GET /labelExplodeObject/{.param*})
+//  (GET /labelExplodeObject/{.param*})
 func (t *testServer) GetLabelExplodeObject(ctx echo.Context, param Object) error {
 	t.object = &param
 	return nil
 }
 
-// (GET /labelNoExplodeArray/{.param})
+//  (GET /labelNoExplodeArray/{.param})
 func (t *testServer) GetLabelNoExplodeArray(ctx echo.Context, param []int32) error {
 	t.array = param
 	return nil
 }
 
-// (GET /labelNoExplodeObject/{.param})
+//  (GET /labelNoExplodeObject/{.param})
 func (t *testServer) GetLabelNoExplodeObject(ctx echo.Context, param Object) error {
 	t.object = &param
 	return nil
 }
 
-// (GET /matrixExplodeArray/{.param*})
+//  (GET /matrixExplodeArray/{.param*})
 func (t *testServer) GetMatrixExplodeArray(ctx echo.Context, param []int32) error {
 	t.array = param
 	return nil
 }
 
-// (GET /matrixExplodeObject/{.param*})
+//  (GET /matrixExplodeObject/{.param*})
 func (t *testServer) GetMatrixExplodeObject(ctx echo.Context, param Object) error {
 	t.object = &param
 	return nil
 }
 
-// (GET /matrixNoExplodeArray/{.param})
+//  (GET /matrixNoExplodeArray/{.param})
 func (t *testServer) GetMatrixNoExplodeArray(ctx echo.Context, param []int32) error {
 	t.array = param
 	return nil
 }
 
-// (GET /matrixNoExplodeObject/{.param})
+//  (GET /matrixNoExplodeObject/{.param})
 func (t *testServer) GetMatrixNoExplodeObject(ctx echo.Context, param Object) error {
 	t.object = &param
 	return nil
 }
 
-// (GET /simpleExplodeArray/{param*})
+//  (GET /simpleExplodeArray/{param*})
 func (t *testServer) GetSimpleExplodeArray(ctx echo.Context, param []int32) error {
 	t.array = param
 	return nil
 }
 
-// (GET /simpleExplodeObject/{param*})
+//  (GET /simpleExplodeObject/{param*})
 func (t *testServer) GetSimpleExplodeObject(ctx echo.Context, param Object) error {
 	t.object = &param
 	return nil
 }
 
-// (GET /simpleNoExplodeArray/{param})
+//  (GET /simpleNoExplodeArray/{param})
 func (t *testServer) GetSimpleNoExplodeArray(ctx echo.Context, param []int32) error {
 	t.array = param
 	return nil
 }
 
-// (GET /simpleNoExplodeObject/{param})
+//  (GET /simpleNoExplodeObject/{param})
 func (t *testServer) GetSimpleNoExplodeObject(ctx echo.Context, param Object) error {
 	t.object = &param
 	return nil
 }
 
-// (GET /passThrough/{param})
+//  (GET /passThrough/{param})
 func (t *testServer) GetPassThrough(ctx echo.Context, param string) error {
 	t.passThrough = &param
 	return nil
 }
 
-// (GET /startingWithjNumber/{param})
+//  (GET /startingWithjNumber/{param})
 func (t *testServer) GetStartingWithNumber(ctx echo.Context, n1param string) error {
 	t.n1param = &n1param
 	return nil
@@ -136,13 +137,13 @@ func (t *testServer) GetDeepObject(ctx echo.Context, params GetDeepObjectParams)
 	return nil
 }
 
-// (GET /simplePrimitive/{param})
+//  (GET /simplePrimitive/{param})
 func (t *testServer) GetSimplePrimitive(ctx echo.Context, param int32) error {
 	t.primitive = &param
 	return nil
 }
 
-// (GET /queryForm)
+//  (GET /queryForm)
 func (t *testServer) GetQueryForm(ctx echo.Context, params GetQueryFormParams) error {
 	t.queryParams = &params
 	if params.Ea != nil {
@@ -175,7 +176,7 @@ func (t *testServer) GetQueryForm(ctx echo.Context, params GetQueryFormParams) e
 	return nil
 }
 
-// (GET /header)
+//  (GET /header)
 func (t *testServer) GetHeader(ctx echo.Context, params GetHeaderParams) error {
 	t.headerParams = &params
 	if params.XPrimitive != nil {
@@ -205,7 +206,7 @@ func (t *testServer) GetHeader(ctx echo.Context, params GetHeaderParams) error {
 	return nil
 }
 
-// (GET /cookie)
+//  (GET /cookie)
 func (t *testServer) GetCookie(ctx echo.Context, params GetCookieParams) error {
 	t.cookieParams = &params
 	if params.Ea != nil {
@@ -261,9 +262,9 @@ func TestParameterBinding(t *testing.T) {
 
 	var expectedPrimitive int32 = 5
 
-	var expectedPrimitiveString = "123;456"
+	var expectedPrimitiveString string = "123;456"
 
-	var expectedN1Param = "foo"
+	var expectedN1Param string = "foo"
 
 	// Check the passthrough case
 	//  (GET /passThrough/{param})
@@ -675,9 +676,9 @@ func TestClientQueryParams(t *testing.T) {
 
 	var expectedPrimitive1 int32 = 5
 	var expectedPrimitive2 int32 = 100
-	var expectedPrimitiveString = "123;456"
+	var expectedPrimitiveString string = "123;456"
 
-	var expectedStartingWithNumber = "111"
+	var expectedStartingWithNumber string = "111"
 
 	// Check query params
 	qParams := GetQueryFormParams{
diff --git a/internal/test/schemas/schemas.yaml b/internal/test/schemas/schemas.yaml
index 3d73527..2428331 100644
--- a/internal/test/schemas/schemas.yaml
+++ b/internal/test/schemas/schemas.yaml
@@ -44,7 +44,7 @@ paths:
         required: false
         content:
           application/json:
-            schema: { }
+            schema: {}
   /issues/30/{fallthrough}:
     get:
       operationId: Issue30
@@ -125,7 +125,7 @@ components:
   schemas:
     GenericObject:
       type: object
-    AnyType1: { }
+    AnyType1: {}
     AnyType2:
       description: |
         AnyType2 represents any type.
@@ -151,7 +151,7 @@ components:
         requiredAndNullable:
           type: string
           nullable: true
-      required: [ required, requiredAndNullable ]
+      required: [required, requiredAndNullable]
     5StartsWithNumber:
       type: object
       description: This schema name starts with a number
@@ -163,8 +163,8 @@ components:
           val:
             type: string
             enum:
-              - first
-              - second
+            - first
+            - second
   parameters:
     StringInPath:
       name: str
@@ -182,5 +182,5 @@ components:
       bearerFormat: |
         JWT-format access token.
 security:
-  - access-token: [ ]
+  - access-token: []
 
diff --git a/internal/test/strict-server/chi/server.go b/internal/test/strict-server/chi/server.go
index 7c8ae2b..748fc7d 100644
--- a/internal/test/strict-server/chi/server.go
+++ b/internal/test/strict-server/chi/server.go
@@ -94,7 +94,7 @@ func (s StrictServer) URLEncodedExample(ctx context.Context, request URLEncodedE
 }
 
 func (s StrictServer) HeadersExample(ctx context.Context, request HeadersExampleRequestObject) (HeadersExampleResponseObject, error) {
-	return HeadersExample200JSONResponse{Body: *request.Body, Headers: HeadersExample200ResponseHeaders{Header1: request.Params.Header1, Header2: *request.Params.Header2}}, nil
+	return HeadersExample200JSONResponse{Body: Example(*request.Body), Headers: HeadersExample200ResponseHeaders{Header1: request.Params.Header1, Header2: *request.Params.Header2}}, nil
 }
 
 func (s StrictServer) ReusableResponses(ctx context.Context, request ReusableResponsesRequestObject) (ReusableResponsesResponseObject, error) {
diff --git a/internal/test/strict-server/gin/server.go b/internal/test/strict-server/gin/server.go
index 7c8ae2b..748fc7d 100644
--- a/internal/test/strict-server/gin/server.go
+++ b/internal/test/strict-server/gin/server.go
@@ -94,7 +94,7 @@ func (s StrictServer) URLEncodedExample(ctx context.Context, request URLEncodedE
 }
 
 func (s StrictServer) HeadersExample(ctx context.Context, request HeadersExampleRequestObject) (HeadersExampleResponseObject, error) {
-	return HeadersExample200JSONResponse{Body: *request.Body, Headers: HeadersExample200ResponseHeaders{Header1: request.Params.Header1, Header2: *request.Params.Header2}}, nil
+	return HeadersExample200JSONResponse{Body: Example(*request.Body), Headers: HeadersExample200ResponseHeaders{Header1: request.Params.Header1, Header2: *request.Params.Header2}}, nil
 }
 
 func (s StrictServer) ReusableResponses(ctx context.Context, request ReusableResponsesRequestObject) (ReusableResponsesResponseObject, error) {
diff --git a/internal/test/strict-server/strict_test.go b/internal/test/strict-server/strict_test.go
index 0075f32..187ca78 100644
--- a/internal/test/strict-server/strict_test.go
+++ b/internal/test/strict-server/strict_test.go
@@ -11,16 +11,17 @@ import (
 	"strings"
 	"testing"
 
+	"github.com/gin-gonic/gin"
+	"github.com/go-chi/chi/v5"
+	"github.com/labstack/echo/v4"
+	"github.com/stretchr/testify/assert"
+
 	"github.com/deepmap/oapi-codegen/internal/test/strict-server/chi"
 	api3 "github.com/deepmap/oapi-codegen/internal/test/strict-server/client"
 	api4 "github.com/deepmap/oapi-codegen/internal/test/strict-server/echo"
 	api2 "github.com/deepmap/oapi-codegen/internal/test/strict-server/gin"
 	"github.com/deepmap/oapi-codegen/pkg/runtime"
 	"github.com/deepmap/oapi-codegen/pkg/testutil"
-	"github.com/gin-gonic/gin"
-	"github.com/go-chi/chi/v5"
-	"github.com/labstack/echo/v4"
-	"github.com/stretchr/testify/assert"
 )
 
 func TestChiServer(t *testing.T) {
diff --git a/pkg/chi-middleware/oapi_validate_test.go b/pkg/chi-middleware/oapi_validate_test.go
index 8d92ba7..d0e804a 100644
--- a/pkg/chi-middleware/oapi_validate_test.go
+++ b/pkg/chi-middleware/oapi_validate_test.go
@@ -10,12 +10,13 @@ import (
 	"net/url"
 	"testing"
 
-	"github.com/deepmap/oapi-codegen/pkg/testutil"
 	"github.com/getkin/kin-openapi/openapi3"
 	"github.com/getkin/kin-openapi/openapi3filter"
 	"github.com/go-chi/chi/v5"
 	"github.com/stretchr/testify/assert"
 	"github.com/stretchr/testify/require"
+
+	"github.com/deepmap/oapi-codegen/pkg/testutil"
 )
 
 //go:embed test_spec.yaml
@@ -55,7 +56,7 @@ func TestOapiRequestValidator(t *testing.T) {
 }
 
 func TestOapiRequestValidatorWithOptionsMultiError(t *testing.T) {
-	swagger, err := openapi3.NewLoader().LoadFromData(testSchema)
+	swagger, err := openapi3.NewLoader().LoadFromData([]byte(testSchema))
 	require.NoError(t, err, "Error initializing swagger")
 
 	r := chi.NewRouter()
@@ -154,7 +155,7 @@ func TestOapiRequestValidatorWithOptionsMultiError(t *testing.T) {
 }
 
 func TestOapiRequestValidatorWithOptionsMultiErrorAndCustomHandler(t *testing.T) {
-	swagger, err := openapi3.NewLoader().LoadFromData(testSchema)
+	swagger, err := openapi3.NewLoader().LoadFromData([]byte(testSchema))
 	require.NoError(t, err, "Error initializing swagger")
 
 	r := chi.NewRouter()
@@ -256,7 +257,7 @@ func TestOapiRequestValidatorWithOptionsMultiErrorAndCustomHandler(t *testing.T)
 }
 
 func TestOapiRequestValidatorWithOptions(t *testing.T) {
-	swagger, err := openapi3.NewLoader().LoadFromData(testSchema)
+	swagger, err := openapi3.NewLoader().LoadFromData([]byte(testSchema))
 	require.NoError(t, err, "Error initializing swagger")
 
 	r := chi.NewRouter()
diff --git a/pkg/chi-middleware/test_spec.yaml b/pkg/chi-middleware/test_spec.yaml
index 6e0a241..3a7b169 100644
--- a/pkg/chi-middleware/test_spec.yaml
+++ b/pkg/chi-middleware/test_spec.yaml
@@ -86,15 +86,15 @@ paths:
             maximum: 100
       responses:
         '200':
-          description: success
-          content:
-            application/json:
-              schema:
-                properties:
-                  name:
-                    type: string
-                  id:
-                    type: integer
+            description: success
+            content:
+              application/json:
+                schema:
+                  properties:
+                    name:
+                      type: string
+                    id:
+                      type: integer
 components:
   securitySchemes:
     BearerAuth:
diff --git a/pkg/codegen/codegen_test.go b/pkg/codegen/codegen_test.go
index 4a85eb1..7b6ee26 100644
--- a/pkg/codegen/codegen_test.go
+++ b/pkg/codegen/codegen_test.go
@@ -8,24 +8,21 @@ import (
 	"net/http"
 	"testing"
 
-	examplePetstoreClient "github.com/deepmap/oapi-codegen/examples/petstore-expanded"
-	examplePetstore "github.com/deepmap/oapi-codegen/examples/petstore-expanded/echo/api"
+	"github.com/stretchr/testify/require"
+
 	"github.com/deepmap/oapi-codegen/pkg/util"
+
 	"github.com/getkin/kin-openapi/openapi3"
 	"github.com/golangci/lint-1"
 	"github.com/stretchr/testify/assert"
-	"github.com/stretchr/testify/require"
-)
 
-const (
-	remoteRefFile = `https://raw.githubusercontent.com/deepmap/oapi-codegen/master/examples/petstore-expanded` +
-		`/petstore-expanded.yaml`
-	remoteRefImport = `github.com/deepmap/oapi-codegen/examples/petstore-expanded`
+	examplePetstoreClient "github.com/deepmap/oapi-codegen/examples/petstore-expanded"
+	examplePetstore "github.com/deepmap/oapi-codegen/examples/petstore-expanded/echo/api"
 )
 
 func checkLint(t *testing.T, filename string, code []byte) {
 	linter := new(lint.Linter)
-	problems, err := linter.Lint(filename, code)
+	problems, err := linter.Lint("test.gen.go", code)
 	assert.NoError(t, err)
 	assert.Len(t, problems, 0)
 }
@@ -193,65 +190,15 @@ type GetTestByNameResponse struct {
 	checkLint(t, "test.gen.go", []byte(code))
 }
 
-func TestGoTypeImport(t *testing.T) {
-	packageName := "api"
-	opts := Configuration{
-		PackageName: packageName,
-		Generate: GenerateOptions{
-			EchoServer:   true,
-			Models:       true,
-			EmbeddedSpec: true,
-		},
-	}
-	spec := "test_specs/x-go-type-import-pet.yaml"
-	swagger, err := util.LoadSwagger(spec)
-	require.NoError(t, err)
-
-	// Run our code generation:
-	code, err := Generate(swagger, opts)
-	assert.NoError(t, err)
-	assert.NotEmpty(t, code)
-
-	// Check that we have valid (formattable) code:
-	_, err = format.Source([]byte(code))
-	assert.NoError(t, err)
-
-	imports := []string{
-		`github.com/CavernaTechnologies/pgext`, // schemas - direct object
-		`myuuid "github.com/google/uuid"`,      // schemas - object
-		`github.com/lib/pq`,                    // schemas - array
-		`github.com/spf13/viper`,               // responses - direct object
-		`golang.org/x/text`,                    // responses - complex object
-		`golang.org/x/email`,                   // requestBodies - in components
-		`github.com/fatih/color`,               // parameters - query
-		`github.com/go-openapi/swag`,           // parameters - path
-		`github.com/jackc/pgtype`,              // direct parameters - path
-		`github.com/mailru/easyjson`,           // direct parameters - query
-		`github.com/subosito/gotenv`,           // direct request body
-	}
-
-	// Check import
-	for _, imp := range imports {
-		assert.Contains(t, code, imp)
-	}
-
-	// Make sure the generated code is valid:
-	checkLint(t, "test.gen.go", []byte(code))
-
-}
-
-func TestRemoteExternalReference(t *testing.T) {
+func TestXGoTypeImport(t *testing.T) {
 	packageName := "api"
 	opts := Configuration{
 		PackageName: packageName,
 		Generate: GenerateOptions{
 			Models: true,
 		},
-		ImportMapping: map[string]string{
-			remoteRefFile: remoteRefImport,
-		},
 	}
-	spec := "test_specs/remote-external-reference.yaml"
+	spec := "test_specs/x-go-type-import-pet.yaml"
 	swagger, err := util.LoadSwagger(spec)
 	require.NoError(t, err)
 
@@ -268,33 +215,19 @@ func TestRemoteExternalReference(t *testing.T) {
 	assert.Contains(t, code, "package api")
 
 	// Check import
-	assert.Contains(t, code, `externalRef0 "github.com/deepmap/oapi-codegen/examples/petstore-expanded"`)
+	assert.Contains(t, code, `myuuid "github.com/google/uuid"`)
 
-	// Check generated oneOf structure:
-	assert.Contains(t, code, `
-// ExampleSchema_Item defines model for ExampleSchema.Item.
-type ExampleSchema_Item struct {
-	union json.RawMessage
-}
-`)
+	// Check generated struct
+	assert.Contains(t, code, "type Pet struct {\n\tAge myuuid.UUID `json:\"age\"`\n}")
 
-	// Check generated oneOf structure As method:
-	assert.Contains(t, code, `
-// AsExternalRef0NewPet returns the union data inside the ExampleSchema_Item as a externalRef0.NewPet
-func (t ExampleSchema_Item) AsExternalRef0NewPet() (externalRef0.NewPet, error) {
-`)
+	// Check import
+	assert.Contains(t, code, `github.com/CavernaTechnologies/pgext`)
 
-	// Check generated oneOf structure From method:
-	assert.Contains(t, code, `
-// FromExternalRef0NewPet overwrites any union data inside the ExampleSchema_Item as the provided externalRef0.NewPet
-func (t *ExampleSchema_Item) FromExternalRef0NewPet(v externalRef0.NewPet) error {
-`)
+	// Check generated struct
+	assert.Contains(t, code, "type Person struct {\n\tAge pgext.Puint `json:\"age\"`\n}")
 
-	// Check generated oneOf structure Merge method:
-	assert.Contains(t, code, `
-// FromExternalRef0NewPet overwrites any union data inside the ExampleSchema_Item as the provided externalRef0.NewPet
-func (t *ExampleSchema_Item) FromExternalRef0NewPet(v externalRef0.NewPet) error {
-`)
+	// Check generated struct
+	assert.Contains(t, code, "type Car struct {\n\tAge int `json:\"age\"`\n}")
 
 	// Make sure the generated code is valid:
 	checkLint(t, "test.gen.go", []byte(code))
diff --git a/pkg/codegen/test_spec.yaml b/pkg/codegen/test_spec.yaml
index 62a9871..b6903e5 100644
--- a/pkg/codegen/test_spec.yaml
+++ b/pkg/codegen/test_spec.yaml
@@ -135,4 +135,4 @@ components:
             tag2: value2
         cause:
           type: string
-          enum: [ car, dog, oldage ]
+          enum: [car, dog, oldage]
diff --git a/pkg/codegen/test_specs/remote-external-reference.yaml b/pkg/codegen/test_specs/remote-external-reference.yaml
deleted file mode 100644
index b966df1..0000000
--- a/pkg/codegen/test_specs/remote-external-reference.yaml
+++ /dev/null
@@ -1,26 +0,0 @@
-openapi: "3.0.0"
-info:
-  version: 1.0.0
-  title: Example with oneOf and external remote ref
-paths:
-  /check:
-    get:
-      summary: Return broken example
-      responses:
-        '200':
-          description: Ok
-          content:
-            application/json:
-              schema:
-                items:
-                  $ref: '#/components/schemas/exampleSchema'
-components:
-  schemas:
-    exampleSchema:
-      properties:
-        item:
-          type: object
-          oneOf:
-            - $ref: 'https://raw.githubusercontent.com/deepmap/oapi-codegen/master/examples/petstore-expanded/petstore-expanded.yaml#/components/schemas/NewPet'
-      required:
-        - item
diff --git a/pkg/codegen/test_specs/x-go-type-import-pet.yaml b/pkg/codegen/test_specs/x-go-type-import-pet.yaml
index b236564..9df66b5 100644
--- a/pkg/codegen/test_specs/x-go-type-import-pet.yaml
+++ b/pkg/codegen/test_specs/x-go-type-import-pet.yaml
@@ -14,111 +14,70 @@ info:
 servers:
   - url: http://petstore.swagger.io/api
 paths:
-  /schemas/pet-object:
+  /pets/{id}:
     get:
-      description: return pet object
+      summary: Returns a pet by ID
+      description: Returns a pet based on a single ID
+      operationId: findPetByID
+      parameters:
+        - name: id
+          in: path
+          description: ID of pet to fetch
+          required: true
+          schema:
+            type: integer
+            format: int64
       responses:
         "200":
-          description: person response
+          description: pet response
           content:
             application/json:
               schema:
-                $ref: "#/components/schemas/PetObject"
-  /schemas/age-simple:
+                $ref: "#/components/schemas/Pet"
+  /person/{id}:
     get:
-      description: return pet object
+      summary: Returns a person by ID
+      description: Returns a person based on a single ID
+      operationId: findPersonByID
+      parameters:
+        - name: id
+          in: path
+          description: ID of person to fetch
+          required: true
+          schema:
+            type: integer
+            format: int64
       responses:
         "200":
           description: person response
           content:
             application/json:
               schema:
-                $ref: "#/components/schemas/AgeSimple"
-
-  /schemas/schema-with-array:
+                $ref: "#/components/schemas/Person"
+  /car/{id}:
     get:
-      description: return schema object with array
+      summary: Returns a car by ID
+      description: Returns a car based on a single ID
+      operationId: findCarByID
+      parameters:
+        - name: id
+          in: path
+          description: ID of car to fetch
+          required: true
+          schema:
+            type: integer
+            format: int64
       responses:
         "200":
-          description: person response
+          description: car response
           content:
             application/json:
               schema:
-                $ref: "#/components/schemas/PetArray"
-
-  /responses/type:
-    get:
-      responses:
-        '200':
-          $ref: '#/components/responses/StringResponse'
-
-  /responses/complex-response:
-    get:
-      responses:
-        '200':
-          $ref: '#/components/responses/ComplexResponse'
-
-  /requests/:
-    post:
-      requestBody:
-        $ref: "#/components/requestBodies/RegisterBody"
-      responses:
-        '200':
-          $ref: '#/components/responses/ComplexResponse'
-
-  /parameters/query:
-    post:
-      parameters:
-        - $ref: "#/components/parameters/Version"
-      requestBody:
-        $ref: "#/components/requestBodies/RegisterBody"
-      responses:
-        '200':
-          $ref: '#/components/responses/ComplexResponse'
-
-  /parameters/{versionPath}:
-    post:
-      parameters:
-        - $ref: "#/components/parameters/VersionPath"
-      requestBody:
-        $ref: "#/components/requestBodies/RegisterBody"
-      responses:
-        '200':
-          $ref: '#/components/responses/ComplexResponse'
-
-  /requests/{path}:
-    post:
-      parameters:
-        - name: version
-          in: query
-          schema:
-            x-go-type: easyjson.Json
-            x-go-type-import:
-              path: github.com/mailru/easyjson
-        - name: path
-          in: path
-          schema:
-            x-go-type: pgtype.Color
-            x-go-type-import:
-              path: github.com/jackc/pgtype
-      requestBody:
-        required: true
-        content:
-          application/json:
-            schema:
-              type: object
-              properties:
-                email:
-                  x-go-type: gotenv.Env
-                  x-go-type-import:
-                    path: github.com/subosito/gotenv
-      responses:
-        '200':
-            $ref: '#/components/responses/ComplexResponse'
+                $ref: "#/components/schemas/Car"
 
 components:
   schemas:
-    PetObject:
+    Pet:
       properties:
         age:
           x-go-type: myuuid.UUID
@@ -127,67 +86,17 @@ components:
             name: myuuid
       required:
         - age
-    AgeSimple:
-      x-go-type: pgext.Puint
-      x-go-type-import:
-        path: github.com/CavernaTechnologies/pgext
-    PetArray:
-      type: array
-      items:
-        x-go-type: pq.Int
-        x-go-type-import:
-          path: github.com/lib/pq
-
-  responses:
-    StringResponse:
-      description: An image.
-      content:
-        application/json:
-          schema:
-            type: string
-            x-go-type: viper.ID
-            x-go-type-import:
-              path: github.com/spf13/viper
-    ComplexResponse:
-      description: Complex response
-      content:
-        application/json:
-          schema:
-            type: object
-            properties:
-              keys:
-                type: array
-                items:
-                  x-go-type: text.Text
-                  x-go-type-import:
-                    path: golang.org/x/text
-
-  requestBodies:
-    RegisterBody:
-      required: true
-      content:
-        application/json:
-          schema:
-            type: object
-            properties:
-              email:
-                x-go-type: email.Email
-                x-go-type-import:
-                  path: golang.org/x/email
-
-  parameters:
-    Version:
-      name: version
-      in: query
-      schema:
-        x-go-type: color.Color
-        x-go-type-import:
-          path: github.com/fatih/color
-
-    VersionPath:
-      name: versionPath
-      in: path
-      schema:
-        x-go-type: swag.Swag
-        x-go-type-import:
-          path: github.com/go-openapi/swag
\ No newline at end of file
+    Person:
+      properties:
+        age:
+          x-go-type: pgext.Puint
+          x-go-type-import:
+            path: github.com/CavernaTechnologies/pgext
+      required:
+        - age
+    Car:
+      properties:
+        age:
+          type: integer
+      required:
+        - age
diff --git a/pkg/codegen/utils_test.go b/pkg/codegen/utils_test.go
index 518e287..7bbfaff 100644
--- a/pkg/codegen/utils_test.go
+++ b/pkg/codegen/utils_test.go
@@ -14,6 +14,8 @@
 package codegen
 
 import (
+	"encoding/json"
+	"fmt"
 	"testing"
 
 	"github.com/getkin/kin-openapi/openapi3"
@@ -432,3 +434,44 @@ func TestSchemaNameToTypeName(t *testing.T) {
 		assert.Equal(t, want, SchemaNameToTypeName(in))
 	}
 }
+
+func TestGetImports(t *testing.T) {
+	schemas := map[string]*openapi3.SchemaRef{
+		"age": {
+			Value: &openapi3.Schema{
+				ExtensionProps: openapi3.ExtensionProps{
+					Extensions: map[string]interface{}{
+						"x-go-type-import": json.RawMessage(
+							`{"name": "hello", "path": "github.com/google/uuid"}`,
+						),
+						"x-go-type": json.RawMessage(
+							"hello.UUID",
+						),
+					},
+				},
+			},
+		},
+		"name": {
+			Value: &openapi3.Schema{
+				ExtensionProps: openapi3.ExtensionProps{
+					Extensions: map[string]interface{}{"other-tag": json.RawMessage(
+						`bla`,
+					)},
+				},
+			},
+		},
+		"value": nil,
+	}
+
+	expected := map[string]goImport{
+		fmt.Sprintf("%s %q", "hello", "github.com/google/uuid"): {
+			Name: "hello",
+			Path: "github.com/google/uuid",
+		},
+	}
+
+	res, err := GetImports(schemas)
+
+	assert.NoError(t, err)
+	assert.Equal(t, expected, res)
+}
diff --git a/pkg/gin-middleware/oapi_validate_test.go b/pkg/gin-middleware/oapi_validate_test.go
index 3ad2f1c..550b23c 100644
--- a/pkg/gin-middleware/oapi_validate_test.go
+++ b/pkg/gin-middleware/oapi_validate_test.go
@@ -25,12 +25,13 @@ import (
 	"net/url"
 	"testing"
 
-	"github.com/deepmap/oapi-codegen/pkg/testutil"
 	"github.com/getkin/kin-openapi/openapi3"
 	"github.com/getkin/kin-openapi/openapi3filter"
 	"github.com/gin-gonic/gin"
 	"github.com/stretchr/testify/assert"
 	"github.com/stretchr/testify/require"
+
+	"github.com/deepmap/oapi-codegen/pkg/testutil"
 )
 
 //go:embed test_spec.yaml
@@ -205,7 +206,7 @@ func TestOapiRequestValidator(t *testing.T) {
 }
 
 func TestOapiRequestValidatorWithOptionsMultiError(t *testing.T) {
-	swagger, err := openapi3.NewLoader().LoadFromData(testSchema)
+	swagger, err := openapi3.NewLoader().LoadFromData([]byte(testSchema))
 	require.NoError(t, err, "Error initializing swagger")
 
 	g := gin.New()
@@ -308,7 +309,7 @@ func TestOapiRequestValidatorWithOptionsMultiError(t *testing.T) {
 }
 
 func TestOapiRequestValidatorWithOptionsMultiErrorAndCustomHandler(t *testing.T) {
-	swagger, err := openapi3.NewLoader().LoadFromData(testSchema)
+	swagger, err := openapi3.NewLoader().LoadFromData([]byte(testSchema))
 	require.NoError(t, err, "Error initializing swagger")
 
 	g := gin.New()
diff --git a/pkg/gin-middleware/test_spec.yaml b/pkg/gin-middleware/test_spec.yaml
index 6e0a241..3a7b169 100644
--- a/pkg/gin-middleware/test_spec.yaml
+++ b/pkg/gin-middleware/test_spec.yaml
@@ -86,15 +86,15 @@ paths:
             maximum: 100
       responses:
         '200':
-          description: success
-          content:
-            application/json:
-              schema:
-                properties:
-                  name:
-                    type: string
-                  id:
-                    type: integer
+            description: success
+            content:
+              application/json:
+                schema:
+                  properties:
+                    name:
+                      type: string
+                    id:
+                      type: integer
 components:
   securitySchemes:
     BearerAuth:
diff --git a/pkg/middleware/oapi_validate_test.go b/pkg/middleware/oapi_validate_test.go
index 8eb5309..a83cfe1 100644
--- a/pkg/middleware/oapi_validate_test.go
+++ b/pkg/middleware/oapi_validate_test.go
@@ -24,13 +24,14 @@ import (
 	"net/url"
 	"testing"
 
-	"github.com/deepmap/oapi-codegen/pkg/testutil"
 	"github.com/getkin/kin-openapi/openapi3"
 	"github.com/getkin/kin-openapi/openapi3filter"
 	"github.com/labstack/echo/v4"
 	echomiddleware "github.com/labstack/echo/v4/middleware"
 	"github.com/stretchr/testify/assert"
 	"github.com/stretchr/testify/require"
+
+	"github.com/deepmap/oapi-codegen/pkg/testutil"
 )
 
 //go:embed test_spec.yaml
@@ -207,7 +208,7 @@ func TestOapiRequestValidator(t *testing.T) {
 }
 
 func TestOapiRequestValidatorWithOptionsMultiError(t *testing.T) {
-	swagger, err := openapi3.NewLoader().LoadFromData(testSchema)
+	swagger, err := openapi3.NewLoader().LoadFromData([]byte(testSchema))
 	require.NoError(t, err, "Error initializing swagger")
 
 	// Create a new echo router
@@ -308,7 +309,7 @@ func TestOapiRequestValidatorWithOptionsMultiError(t *testing.T) {
 }
 
 func TestOapiRequestValidatorWithOptionsMultiErrorAndCustomHandler(t *testing.T) {
-	swagger, err := openapi3.NewLoader().LoadFromData(testSchema)
+	swagger, err := openapi3.NewLoader().LoadFromData([]byte(testSchema))
 	require.NoError(t, err, "Error initializing swagger")
 
 	// Create a new echo router
diff --git a/pkg/middleware/test_spec.yaml b/pkg/middleware/test_spec.yaml
index 1f847d7..7c8ea6a 100644
--- a/pkg/middleware/test_spec.yaml
+++ b/pkg/middleware/test_spec.yaml
@@ -86,15 +86,15 @@ paths:
             maximum: 100
       responses:
         '200':
-          description: success
-          content:
-            application/json:
-              schema:
-                properties:
-                  name:
-                    type: string
-                  id:
-                    type: integer
+            description: success
+            content:
+              application/json:
+                schema:
+                  properties:
+                    name:
+                      type: string
+                    id:
+                      type: integer
 components:
   securitySchemes:
     BearerAuth:
diff --git a/pkg/runtime/bindform_test.go b/pkg/runtime/bindform_test.go
index 9660ce4..ac47ef2 100644
--- a/pkg/runtime/bindform_test.go
+++ b/pkg/runtime/bindform_test.go
@@ -6,8 +6,9 @@ import (
 	"net/url"
 	"testing"
 
-	"github.com/deepmap/oapi-codegen/pkg/types"
 	"github.com/stretchr/testify/assert"
+
+	"github.com/deepmap/oapi-codegen/pkg/types"
 )
 
 func TestBindURLForm(t *testing.T) {
diff --git a/pkg/runtime/bindparam_test.go b/pkg/runtime/bindparam_test.go
index 2334c50..c745e18 100644
--- a/pkg/runtime/bindparam_test.go
+++ b/pkg/runtime/bindparam_test.go
@@ -21,9 +21,10 @@ import (
 	"testing"
 	"time"
 
-	"github.com/deepmap/oapi-codegen/pkg/types"
 	"github.com/stretchr/testify/assert"
 	"github.com/stretchr/testify/require"
+
+	"github.com/deepmap/oapi-codegen/pkg/types"
 )
 
 // MockBinder is just an independent version of Binder that has the Bind implemented
diff --git a/pkg/runtime/bindstring_test.go b/pkg/runtime/bindstring_test.go
index 0ce0914..f2060de 100644
--- a/pkg/runtime/bindstring_test.go
+++ b/pkg/runtime/bindstring_test.go
@@ -19,8 +19,9 @@ import (
 	"testing"
 	"time"
 
-	"github.com/deepmap/oapi-codegen/pkg/types"
 	"github.com/stretchr/testify/assert"
+
+	"github.com/deepmap/oapi-codegen/pkg/types"
 )
 
 func TestBindStringToObject(t *testing.T) {
diff --git a/pkg/runtime/styleparam_test.go b/pkg/runtime/styleparam_test.go
index 5500820..6271fb7 100644
--- a/pkg/runtime/styleparam_test.go
+++ b/pkg/runtime/styleparam_test.go
@@ -17,9 +17,10 @@ import (
 	"testing"
 	"time"
 
-	"github.com/deepmap/oapi-codegen/pkg/types"
 	"github.com/google/uuid"
 	"github.com/stretchr/testify/assert"
+
+	"github.com/deepmap/oapi-codegen/pkg/types"
 )
 
 func TestStyleParam(t *testing.T) {
@@ -44,7 +45,7 @@ func TestStyleParam(t *testing.T) {
 	timestamp := AliasedTime(ti)
 
 	type AliasedDate types.Date
-	date := AliasedDate{Time: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC)}
+	date := AliasedDate{time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC)}
 
 	type AliasedUUID types.UUID
 	aUUID := AliasedUUID(uuid.MustParse("baa07328-452e-40bd-aa2e-fa823ec13605"))
@@ -669,7 +670,7 @@ func TestStyleParam(t *testing.T) {
 	object3 := testObject3{
 		TimeField: timeVal,
 		DateField: dateVal,
-		UUIDField: uuidVal,
+		UUIDField: uuid.UUID(uuidVal),
 	}
 
 	result, err = StyleParamWithLocation("simple", false, "id", ParamLocationQuery, object3)
diff --git a/pkg/securityprovider/securityprovider_test.go b/pkg/securityprovider/securityprovider_test.go
index 0bb3d3c..efea758 100644
--- a/pkg/securityprovider/securityprovider_test.go
+++ b/pkg/securityprovider/securityprovider_test.go
@@ -8,7 +8,7 @@ import (
 )
 
 var (
-	withTrailingSlash = "https://my-api.com/some-base-url/v1/"
+	withTrailingSlash string = "https://my-api.com/some-base-url/v1/"
 )
 
 func TestSecurityProviders(t *testing.T) {
diff --git a/pkg/testutil/request_helpers.go b/pkg/testutil/request_helpers.go
index e0f8c08..1735026 100644
--- a/pkg/testutil/request_helpers.go
+++ b/pkg/testutil/request_helpers.go
@@ -42,7 +42,7 @@ func NewRequest() *RequestBuilder {
 	}
 }
 
-// RequestBuilder caches request settings as we build up the request.
+// This structure caches request settings as we build up the request.
 type RequestBuilder struct {
 	Method  string
 	Path    string
@@ -52,7 +52,7 @@ type RequestBuilder struct {
 	Cookies []*http.Cookie
 }
 
-// WithMethod sets the method and path
+// Path operations
 func (r *RequestBuilder) WithMethod(method string, path string) *RequestBuilder {
 	r.Method = method
 	r.Path = path
@@ -79,7 +79,7 @@ func (r *RequestBuilder) Delete(path string) *RequestBuilder {
 	return r.WithMethod("DELETE", path)
 }
 
-// WithHeader sets a header
+// Header operations
 func (r *RequestBuilder) WithHeader(header, value string) *RequestBuilder {
 	r.Headers[header] = value
 	return r
@@ -117,7 +117,7 @@ func (r *RequestBuilder) WithBody(body []byte) *RequestBuilder {
 	return r
 }
 
-// WithJsonBody takes an object as input, marshals it to JSON, and sends it
+// This function takes an object as input, marshals it to JSON, and sends it
 // as the body with Content-Type: application/json
 func (r *RequestBuilder) WithJsonBody(obj interface{}) *RequestBuilder {
 	var err error
@@ -128,7 +128,7 @@ func (r *RequestBuilder) WithJsonBody(obj interface{}) *RequestBuilder {
 	return r.WithJsonContentType()
 }
 
-// WithCookie sets a cookie
+// Cookie operations
 func (r *RequestBuilder) WithCookie(c *http.Cookie) *RequestBuilder {
 	r.Cookies = append(r.Cookies, c)
 	return r
@@ -176,7 +176,7 @@ func (r *RequestBuilder) Go(t *testing.T, e *echo.Echo) *CompletedRequest {
 	return r.GoWithHTTPHandler(t, e)
 }
 
-// CompletedRequest is the result of calling Go() on the request builder. We're wrapping the
+// This is the result of calling Go() on the request builder. We're wrapping the
 // ResponseRecorder with some nice helper functions.
 type CompletedRequest struct {
 	Recorder *httptest.ResponseRecorder
@@ -190,7 +190,7 @@ func (c *CompletedRequest) DisallowUnknownFields() {
 	c.Strict = true
 }
 
-// UnmarshalBodyToObject takes a destination object as input, and unmarshals the object
+// This function takes a destination object as input, and unmarshals the object
 // in the response based on the Content-Type header.
 func (c *CompletedRequest) UnmarshalBodyToObject(obj interface{}) error {
 	ctype := c.Recorder.Header().Get("Content-Type")
@@ -206,13 +206,13 @@ func (c *CompletedRequest) UnmarshalBodyToObject(obj interface{}) error {
 	return handler(ctype, c.Recorder.Body, obj, c.Strict)
 }
 
-// UnmarshalJsonToObject assumes that the response contains JSON and unmarshals it
+// This function assumes that the response contains JSON and unmarshals it
 // into the specified object.
 func (c *CompletedRequest) UnmarshalJsonToObject(obj interface{}) error {
 	return json.Unmarshal(c.Recorder.Body.Bytes(), obj)
 }
 
-// Code is a shortcut for response code
+// Shortcut for response code
 func (c *CompletedRequest) Code() int {
 	return c.Recorder.Code
 }