knife4gin.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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 Register(r *gin.Engine, option *Option) {
  22. r.GET(option.RelativePath+"/*any", Handler(option))
  23. }
  24. func Handler(option *Option) gin.HandlerFunc {
  25. if option.DocJsonPath == "" {
  26. option.DocJsonPath = "./doc/swagger.json"
  27. }
  28. docJson, err := os.ReadFile(option.DocJsonPath)
  29. if err != nil {
  30. log.Printf("not found docJson in " + option.DocJsonPath)
  31. }
  32. indexPath := option.RelativePath + "/index.html"
  33. servicesPath := option.RelativePath + "/services.json"
  34. docJsonPath := option.RelativePath + "/doc.json"
  35. return func(c *gin.Context) {
  36. switch c.Request.RequestURI {
  37. case indexPath:
  38. writeDocHtml(c)
  39. case servicesPath:
  40. writeServicesJson(c)
  41. case docJsonPath:
  42. writeDocJson(c, docJson)
  43. default:
  44. //filePath := strings.ReplaceAll(c.Request.RequestURI, option.RelativePath, "")
  45. filePath := strings.TrimPrefix(c.Request.RequestURI, option.RelativePath)
  46. c.FileFromFS(filePath, http.FS(front))
  47. }
  48. }
  49. }
  50. func writeBytes(write io.Writer, bytes []byte) {
  51. _, err := write.Write(bytes)
  52. log.Printf("文件写入失败%+v", err)
  53. }
  54. func writeDocHtml(c *gin.Context) {
  55. docHtml, err := front.ReadFile("doc.html")
  56. if err != nil {
  57. writeBytes(c.Writer, []byte(err.Error()))
  58. }
  59. writeBytes(c.Writer, docHtml)
  60. }
  61. func writeDocJson(c *gin.Context, docJson []byte) {
  62. writeBytes(c.Writer, docJson)
  63. }
  64. func writeServicesJson(c *gin.Context) {
  65. var res []map[string]any
  66. res = append(res, map[string]any{
  67. "name": "2.X版本",
  68. "url": "doc.json",
  69. "swaggerVersion": "2.0",
  70. "location": "doc.json",
  71. })
  72. c.JSON(http.StatusOK, res)
  73. }