-
Notifications
You must be signed in to change notification settings - Fork 0
/
swag.go
70 lines (64 loc) · 1.63 KB
/
swag.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
67
68
69
70
package apidoc
import (
"encoding/json"
"io/ioutil"
"net/http"
"path"
"strings"
"github.com/go-openapi/loads"
"github.com/go-openapi/runtime/middleware"
"github.com/go-openapi/spec"
"github.com/hopeio/cherry/utils/log"
)
var PrefixUri = "/api-doc/"
var FilePath = "./api/"
const swagger = "swagger"
const EXT = ".swagger.json"
func HttpHandle(w http.ResponseWriter, r *http.Request) {
prefixUri := PrefixUri + swagger + "/"
if r.RequestURI[len(r.RequestURI)-5:] == ".json" {
specDoc, err := loads.Spec(FilePath + r.RequestURI[len(prefixUri):])
if err != nil {
w.Write([]byte(err.Error()))
return
}
specDoc, err = specDoc.Expanded(&spec.ExpandOptions{
SkipSchemas: false,
ContinueOnError: true,
AbsoluteCircularRef: true,
})
if err != nil {
w.Write([]byte(err.Error()))
return
}
b, err := json.MarshalIndent(specDoc.Spec(), "", " ")
if err != nil {
w.Write([]byte(err.Error()))
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
//#nosec
_, _ = w.Write(b)
return
}
mod := r.RequestURI[len(prefixUri):]
middleware.Redoc(middleware.RedocOpts{
BasePath: prefixUri,
SpecURL: path.Join(prefixUri+mod, mod+EXT),
Path: mod,
}, http.NotFoundHandler()).ServeHTTP(w, r)
}
func ApiMod(w http.ResponseWriter, r *http.Request) {
fileInfos, err := ioutil.ReadDir(FilePath)
if err != nil {
log.Error(err)
}
var ret []string
for i := range fileInfos {
if fileInfos[i].IsDir() {
ret = append(ret, `<a href="`+r.RequestURI+"/"+fileInfos[i].Name()+`">`+fileInfos[i].Name()+`</a>`)
}
}
w.Write([]byte(strings.Join(ret, "<br>")))
}