-
Notifications
You must be signed in to change notification settings - Fork 0
/
swagger.go
66 lines (54 loc) · 1.53 KB
/
swagger.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package echo_swagger
import (
"encoding/json"
"errors"
"fmt"
"github.com/go-openapi/loads"
"github.com/go-openapi/runtime/middleware"
"github.com/gorilla/handlers"
"github.com/labstack/echo/v4"
"net/http"
"os"
"path"
)
type Middleware struct {
FilePath string
BasePath string
}
func (s *Middleware) swaggerUIHandler(opts middleware.SwaggerUIOpts) http.Handler {
return middleware.SwaggerUI(opts, nil)
}
func (s *Middleware) swaggerSpecFileHandler(swaggerUiHandler http.Handler) (http.Handler, error) {
if _, err := os.Stat(s.FilePath); os.IsNotExist(err) {
return nil, errors.New(fmt.Sprintf("%s file is not exist", s.FilePath))
}
specDoc, err := loads.Spec(s.FilePath)
if err != nil {
return nil, err
}
b, err := json.MarshalIndent(specDoc.Spec(), "", " ")
if err != nil {
return nil, err
}
return handlers.CORS()(middleware.Spec(s.BasePath, b, swaggerUiHandler)), nil
}
func (s *Middleware) Register(app *echo.Echo) {
swaggerUIOpts := middleware.SwaggerUIOpts{
BasePath: s.BasePath,
SpecURL: path.Join(s.BasePath, "swagger.json"),
Path: "docs",
}
swaggerUiHandler := s.swaggerUIHandler(swaggerUIOpts)
specFileHandler, err := s.swaggerSpecFileHandler(swaggerUiHandler)
if err != nil {
panic(err)
}
app.GET(path.Join(s.BasePath, swaggerUIOpts.Path), echo.WrapHandler(swaggerUiHandler))
app.GET(path.Join(s.BasePath, "swagger.json"), echo.WrapHandler(specFileHandler))
}
func NewMiddleware(fileName string, basePath string) *Middleware {
return &Middleware{
FilePath: fileName,
BasePath: basePath,
}
}