-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
77 lines (70 loc) · 2.22 KB
/
handler.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
71
72
73
74
75
76
77
package apidoc
import (
"bytes"
"github.com/go-openapi/runtime/middleware"
"net/http"
"os"
"path"
)
// 目录结构 ./api/mod/mod.swagger.json ./api/mod/mod.apidoc.md
// 请求路由 /api-doc /api-doc/swagger/mod/mod.swagger.json /api-doc/markdown/mod/mod.apidoc.md
var UriPrefix = "/api-doc"
var ApiDocDir = "./apidoc/"
const TypeSwagger = "swagger"
const TypeMarkdown = "markdown"
const SwaggerEXT = ".swagger.json"
const MarkDownEXT = ".apidoc.md"
func Swagger(w http.ResponseWriter, r *http.Request) {
prefixUri := UriPrefix + "/" + TypeSwagger + "/"
if r.RequestURI[len(r.RequestURI)-5:] == ".json" {
b, err := os.ReadFile(ApiDocDir + r.RequestURI[len(prefixUri):])
if err != nil {
w.Write([]byte(err.Error()))
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusOK)
w.Write(b)
return
}
mod := r.RequestURI[len(prefixUri):]
middleware.Redoc(middleware.RedocOpts{
BasePath: prefixUri,
SpecURL: path.Join(prefixUri+mod, mod+SwaggerEXT),
Path: mod,
}, http.NotFoundHandler()).ServeHTTP(w, r)
}
func Markdown(w http.ResponseWriter, r *http.Request) {
prefixUri := UriPrefix + "/" + TypeMarkdown + "/"
mod := r.RequestURI[len(prefixUri):]
b, err := os.ReadFile(ApiDocDir + mod + "/" + mod + MarkDownEXT)
if err != nil {
w.Write([]byte(err.Error()))
return
}
w.Header().Set("Content-Type", "text/markdown; charset=utf-8")
w.WriteHeader(http.StatusOK)
w.Write(b)
return
}
func DocList(w http.ResponseWriter, r *http.Request) {
fileInfos, err := os.ReadDir(ApiDocDir)
if err != nil {
w.Write([]byte(err.Error()))
return
}
var buff bytes.Buffer
for i := range fileInfos {
if fileInfos[i].IsDir() {
buff.Write([]byte(`<a href="` + r.RequestURI + "/swagger/" + fileInfos[i].Name() + `"> swagger: ` + fileInfos[i].Name() + `</a><br>`))
buff.Write([]byte(`<a href="` + r.RequestURI + "/markdown/" + fileInfos[i].Name() + `"> markdown: ` + fileInfos[i].Name() + `</a><br>`))
}
}
w.Write(buff.Bytes())
}
func OpenApi(mux *http.ServeMux, filePath string) {
ApiDocDir = filePath
mux.Handle(UriPrefix, http.HandlerFunc(DocList))
mux.Handle(UriPrefix+"/markdown/", http.HandlerFunc(Markdown))
mux.Handle(UriPrefix+"/swagger/", http.HandlerFunc(Swagger))
}