fix: 修复了当文件名为index.html时被golang贴心自动重定向的bug

This commit is contained in:
539943419 committed 2024-08-23 19:42:35 +08:00
1 parent 817603cade
commit 871906808c
1 file changed
+61 -49
+61 -49
View File
@@ -1,59 +1,71 @@
package api package api
import ( import (
"github.com/gin-gonic/gin" "io/ioutil"
"net/http" "net/http"
"os" "os"
"path/filepath" "path/filepath"
"io/ioutil" "strings"
"time"
"github.com/gin-gonic/gin"
) )
func GetHandler(c *gin.Context) { func GetHandler(c *gin.Context) {
decodedPath, err := filepath.Abs(filepath.Join(staticPath, c.Param("path"))) decodedPath, err := filepath.Abs(filepath.Join(staticPath, c.Param("path")))
if err != nil { if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Unable to access path"}) c.JSON(http.StatusInternalServerError, gin.H{"error": "Unable to access path"})
return return
} }
fileInfo, err := os.Stat(decodedPath) fileInfo, err := os.Stat(decodedPath)
if os.IsNotExist(err) { if os.IsNotExist(err) {
c.JSON(http.StatusNotFound, gin.H{"error": "Path not found"}) c.JSON(http.StatusNotFound, gin.H{"error": "Path not found"})
return return
} }
if fileInfo.IsDir() { if fileInfo.IsDir() {
files, err := ioutil.ReadDir(decodedPath) files, err := ioutil.ReadDir(decodedPath)
if err != nil { if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Unable to scan directory"}) c.JSON(http.StatusInternalServerError, gin.H{"error": "Unable to scan directory"})
return return
} }
var fileDetails []gin.H var fileDetails []gin.H
for _, file := range files { for _, file := range files {
fileDetails = append(fileDetails, gin.H{ fileDetails = append(fileDetails, gin.H{
"name": file.Name(), "name": file.Name(),
"size": file.Size(), "size": file.Size(),
"type": func() string { "type": func() string {
if file.IsDir() { if file.IsDir() {
return "directory" return "directory"
} }
return "file" return "file"
}(), }(),
"stats": gin.H{ "stats": gin.H{
"atimeMs": file.ModTime().UnixNano() / 1e6, "atimeMs": file.ModTime().UnixNano() / 1e6,
"birthtimeMs": file.ModTime().UnixNano() / 1e6, "birthtimeMs": file.ModTime().UnixNano() / 1e6,
"ctimeMs": file.ModTime().UnixNano() / 1e6, "ctimeMs": file.ModTime().UnixNano() / 1e6,
"mtimeMs": file.ModTime().UnixNano() / 1e6, "mtimeMs": file.ModTime().UnixNano() / 1e6,
}, },
}) })
} }
if len(fileDetails) == 0 { if len(fileDetails) == 0 {
c.JSON(http.StatusOK, []gin.H{}) c.JSON(http.StatusOK, []gin.H{})
} else { } else {
c.JSON(http.StatusOK, fileDetails) c.JSON(http.StatusOK, fileDetails)
} }
} else { } else {
c.File(decodedPath) if strings.HasSuffix(decodedPath, "index.html") {
} f, err := os.Open(decodedPath)
if err != nil {
c.Writer.WriteHeader(http.StatusInternalServerError)
c.Writer.Write([]byte("Internal Server Error"))
return
}
http.ServeContent(c.Writer, c.Request, "index.html", time.Now(), f)
} else {
c.File(decodedPath)
}
}
} }