115 lines
2.2 KiB
Go
115 lines
2.2 KiB
Go
package api
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"codespace/internal/model"
|
|
"codespace/internal/service"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
type fileHandler struct {
|
|
svc *service.FileService
|
|
}
|
|
|
|
func (h *fileHandler) list(c *gin.Context) {
|
|
id := c.Param("id")
|
|
path := c.Query("path")
|
|
if path == "" {
|
|
path = "."
|
|
}
|
|
infos, err := h.svc.List(id, path)
|
|
if err != nil {
|
|
writeError(c, err)
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, infos)
|
|
}
|
|
|
|
func (h *fileHandler) read(c *gin.Context) {
|
|
id := c.Param("id")
|
|
path := c.Query("path")
|
|
if path == "" {
|
|
writeBadRequest(c, "path is required")
|
|
return
|
|
}
|
|
data, err := h.svc.Read(id, path)
|
|
if err != nil {
|
|
writeError(c, err)
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, model.ReadFileResponse{
|
|
Path: path,
|
|
Content: string(data),
|
|
})
|
|
}
|
|
|
|
func (h *fileHandler) write(c *gin.Context) {
|
|
id := c.Param("id")
|
|
var req model.WriteFileRequest
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
writeBadRequest(c, "invalid json")
|
|
return
|
|
}
|
|
if req.Path == "" {
|
|
writeBadRequest(c, "path is required")
|
|
return
|
|
}
|
|
if err := h.svc.Write(id, req.Path, []byte(req.Content)); err != nil {
|
|
writeError(c, err)
|
|
return
|
|
}
|
|
c.Status(http.StatusNoContent)
|
|
}
|
|
|
|
func (h *fileHandler) mkdir(c *gin.Context) {
|
|
id := c.Param("id")
|
|
var req model.MkdirRequest
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
writeBadRequest(c, "invalid json")
|
|
return
|
|
}
|
|
if req.Path == "" {
|
|
writeBadRequest(c, "path is required")
|
|
return
|
|
}
|
|
if err := h.svc.Mkdir(id, req.Path); err != nil {
|
|
writeError(c, err)
|
|
return
|
|
}
|
|
c.Status(http.StatusNoContent)
|
|
}
|
|
|
|
func (h *fileHandler) remove(c *gin.Context) {
|
|
id := c.Param("id")
|
|
path := c.Query("path")
|
|
if path == "" {
|
|
writeBadRequest(c, "path is required")
|
|
return
|
|
}
|
|
if err := h.svc.Remove(id, path); err != nil {
|
|
writeError(c, err)
|
|
return
|
|
}
|
|
c.Status(http.StatusNoContent)
|
|
}
|
|
|
|
func (h *fileHandler) rename(c *gin.Context) {
|
|
id := c.Param("id")
|
|
var req model.RenameRequest
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
writeBadRequest(c, "invalid json")
|
|
return
|
|
}
|
|
if req.OldPath == "" || req.NewPath == "" {
|
|
writeBadRequest(c, "oldPath and newPath are required")
|
|
return
|
|
}
|
|
if err := h.svc.Rename(id, req.OldPath, req.NewPath); err != nil {
|
|
writeError(c, err)
|
|
return
|
|
}
|
|
c.Status(http.StatusNoContent)
|
|
}
|