Files
filer/internal/handler/handler.go
2023-10-20 22:35:34 +02:00

59 lines
1.0 KiB
Go

package handler
import (
"net/http"
"os"
"path/filepath"
// "strings"
"filer/pkg/logger"
"github.com/gin-gonic/gin"
)
type HandlerConfig struct {
Datadir string
}
type Handler struct {
log *logger.Logger
datadir string
}
func NewHandler(conf *HandlerConfig) (*Handler, error) {
var err error
hand := &Handler{
datadir: conf.Datadir,
log: logger.NewLogger("handler"),
}
return hand, err
}
func (hand *Handler) GetFile(gctx *gin.Context) {
filePath := gctx.Request.URL.Path
localFilePath := filepath.Join(hand.datadir, filePath)
hand.log.Debugf("Send file %s", localFilePath)
// if strings.Contains(localFilePath, "/../") {
// gctx.Status(http.StatusBadRequest)
// return
// }
if filePath != "" && fileExists(localFilePath) {
gctx.FileAttachment(localFilePath, filepath.Base(filePath))
return
} else {
gctx.Status(http.StatusNotFound)
return
}
}
func fileExists(name string) bool {
fi, err := os.Stat(name)
if err != nil {
if os.IsNotExist(err) {
return false
}
}
return !fi.IsDir()
}