knife4gin.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package knife4gin
  2. import (
  3. "embed"
  4. "github.com/gin-gonic/gin"
  5. "io"
  6. "log"
  7. "net/http"
  8. "os"
  9. "strings"
  10. )
  11. //go:embed front
  12. var front embed.FS
  13. type Option struct {
  14. DocJsonPath string
  15. RelativePath string
  16. }
  17. //func InitDoc1(r *gin.Engine) {
  18. // r.GET("", Handler(&Option{DocJsonPath: "", RelativePath: ""}))
  19. //
  20. //}
  21. func Handler(option *Option) gin.HandlerFunc {
  22. if option.DocJsonPath == "" {
  23. option.DocJsonPath = "./doc/swagger.json"
  24. }
  25. docJson, err := os.ReadFile(option.DocJsonPath)
  26. if err != nil {
  27. log.Printf("not found docJson in " + option.DocJsonPath)
  28. }
  29. return func(c *gin.Context) {
  30. switch c.Request.RequestURI {
  31. case "index.html":
  32. writeDocHtml(c)
  33. case "services.json":
  34. writeServicesJson(c)
  35. case "doc.json":
  36. writeDocJson(c, docJson)
  37. default:
  38. filePath := strings.ReplaceAll(c.Request.RequestURI, option.RelativePath, "")
  39. c.FileFromFS(filePath, http.FS(front))
  40. }
  41. }
  42. }
  43. func writeBytes(write io.Writer, bytes []byte) {
  44. _, err := write.Write(bytes)
  45. log.Printf("文件写入失败%+v", err)
  46. }
  47. func writeDocHtml(c *gin.Context) {
  48. docHtml, err := front.ReadFile("doc.html")
  49. if err != nil {
  50. writeBytes(c.Writer, []byte(err.Error()))
  51. }
  52. writeBytes(c.Writer, docHtml)
  53. }
  54. func writeDocJson(c *gin.Context, docJson []byte) {
  55. writeBytes(c.Writer, docJson)
  56. }
  57. func writeServicesJson(c *gin.Context) {
  58. var res []map[string]any
  59. res = append(res, map[string]any{
  60. "name": "2.X版本",
  61. "url": "doc.json",
  62. "swaggerVersion": "2.0",
  63. "location": "doc.json",
  64. })
  65. c.JSON(http.StatusOK, res)
  66. }