-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
ghttp_server_swagger.go
55 lines (50 loc) · 1.61 KB
/
ghttp_server_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
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package ghttp
import (
"fmt"
"github.com/gogf/gf/v2/text/gstr"
)
const (
swaggerUIDocName = `redoc.standalone.js`
swaggerUIDocNamePlaceHolder = `{SwaggerUIDocName}`
swaggerUIDocURLPlaceHolder = `{SwaggerUIDocUrl}`
swaggerUITemplate = `
<!DOCTYPE html>
<html>
<head>
<title>API Reference</title>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<redoc spec-url="{SwaggerUIDocUrl}" show-object-schema-examples="true"></redoc>
<script src="https://unpkg.com/redoc@2.0.0-rc.70/bundles/redoc.standalone.js"> </script>
</body>
</html>
`
)
// swaggerUI is a build-in hook handler for replace default swagger json URL to local openapi json file path.
// This handler makes sense only if the openapi specification automatic producing configuration is enabled.
func (s *Server) swaggerUI(r *Request) {
if s.config.OpenApiPath == "" {
return
}
if r.StaticFile != nil && r.StaticFile.File != nil && r.StaticFile.IsDir {
content := gstr.ReplaceByMap(swaggerUITemplate, map[string]string{
swaggerUIDocURLPlaceHolder: s.config.OpenApiPath,
swaggerUIDocNamePlaceHolder: gstr.TrimRight(fmt.Sprintf(`//%s%s`, r.Host, r.Server.config.SwaggerPath), "/") + "/" + swaggerUIDocName,
})
r.Response.Write(content)
r.ExitAll()
}
}