knife4gin.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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 := "front" + strings.TrimPrefix(c.Request.RequestURI, option.RelativePath)
  45. c.FileFromFS(filePath, http.FS(front))
  46. }
  47. }
  48. }
  49. func writeBytes(write io.Writer, bytes []byte) {
  50. _, err := write.Write(bytes)
  51. log.Printf("文件写入失败%+v", err)
  52. }
  53. func writeDocHtml(c *gin.Context) {
  54. docHtml, err := front.ReadFile("front/doc.html")
  55. if err != nil {
  56. writeBytes(c.Writer, []byte(err.Error()))
  57. }
  58. writeBytes(c.Writer, docHtml)
  59. }
  60. func writeDocJson(c *gin.Context, docJson []byte) {
  61. writeBytes(c.Writer, docJson)
  62. }
  63. func writeServicesJson(c *gin.Context) {
  64. var res []map[string]any
  65. res = append(res, map[string]any{
  66. "name": "2.X版本",
  67. "url": "doc.json",
  68. "swaggerVersion": "2.0",
  69. "location": "doc.json",
  70. })
  71. c.JSON(http.StatusOK, res)
  72. }