12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- package knife4gin
- import (
- "embed"
- "github.com/gin-gonic/gin"
- "io"
- "log"
- "net/http"
- "os"
- "strings"
- )
- //go:embed front
- var front embed.FS
- type Option struct {
- DocJsonPath string
- RelativePath string
- }
- //func InitDoc1(r *gin.Engine) {
- // r.GET("", Handler(&Option{DocJsonPath: "", RelativePath: ""}))
- //
- //}
- func Handler(option *Option) gin.HandlerFunc {
- if option.DocJsonPath == "" {
- option.DocJsonPath = "./doc/swagger.json"
- }
- docJson, err := os.ReadFile(option.DocJsonPath)
- if err != nil {
- log.Printf("not found docJson in " + option.DocJsonPath)
- }
- return func(c *gin.Context) {
- switch c.Request.RequestURI {
- case "index.html":
- writeDocHtml(c)
- case "services.json":
- writeServicesJson(c)
- case "doc.json":
- writeDocJson(c, docJson)
- default:
- filePath := strings.ReplaceAll(c.Request.RequestURI, option.RelativePath, "")
- c.FileFromFS(filePath, http.FS(front))
- }
- }
- }
- func writeBytes(write io.Writer, bytes []byte) {
- _, err := write.Write(bytes)
- log.Printf("文件写入失败%+v", err)
- }
- func writeDocHtml(c *gin.Context) {
- docHtml, err := front.ReadFile("doc.html")
- if err != nil {
- writeBytes(c.Writer, []byte(err.Error()))
- }
- writeBytes(c.Writer, docHtml)
- }
- func writeDocJson(c *gin.Context, docJson []byte) {
- writeBytes(c.Writer, docJson)
- }
- func writeServicesJson(c *gin.Context) {
- var res []map[string]any
- res = append(res, map[string]any{
- "name": "2.X版本",
- "url": "doc.json",
- "swaggerVersion": "2.0",
- "location": "doc.json",
- })
- c.JSON(http.StatusOK, res)
- }
|