...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package middleware
16
17 import (
18 "net/http"
19 "path"
20 )
21
22 const (
23 contentTypeHeader = "Content-Type"
24 applicationJSON = "application/json"
25 )
26
27
28 type SpecOption func(*specOptions)
29
30 var defaultSpecOptions = specOptions{
31 Path: "",
32 Document: "swagger.json",
33 }
34
35 type specOptions struct {
36 Path string
37 Document string
38 }
39
40 func specOptionsWithDefaults(opts []SpecOption) specOptions {
41 o := defaultSpecOptions
42 for _, apply := range opts {
43 apply(&o)
44 }
45
46 return o
47 }
48
49
50
51
52
53
54
55 func Spec(basePath string, b []byte, next http.Handler, opts ...SpecOption) http.Handler {
56 if basePath == "" {
57 basePath = "/"
58 }
59 o := specOptionsWithDefaults(opts)
60 pth := path.Join(basePath, o.Path, o.Document)
61
62 return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
63 if path.Clean(r.URL.Path) == pth {
64 rw.Header().Set(contentTypeHeader, applicationJSON)
65 rw.WriteHeader(http.StatusOK)
66 _, _ = rw.Write(b)
67
68 return
69 }
70
71 if next != nil {
72 next.ServeHTTP(rw, r)
73
74 return
75 }
76
77 rw.Header().Set(contentTypeHeader, applicationJSON)
78 rw.WriteHeader(http.StatusNotFound)
79 })
80 }
81
82
83
84
85 func WithSpecPath(pth string) SpecOption {
86 return func(o *specOptions) {
87 o.Path = pth
88 }
89 }
90
91
92
93
94 func WithSpecDocument(doc string) SpecOption {
95 return func(o *specOptions) {
96 if doc == "" {
97 return
98 }
99
100 o.Document = doc
101 }
102 }
103
View as plain text