personal-website/libs/cat.go

65 lines
1.1 KiB
Go

package libs
import (
"errors"
"net/http"
"personalwebsite/webfilesystem"
"github.com/gin-gonic/gin"
)
//TODO Use this to get json from back
type Cat struct {
fs *webfilesystem.WebFileSystem
}
func NewCatLib(webfs *webfilesystem.WebFileSystem) *Cat {
return &Cat{
fs: webfs,
}
}
func (c *Cat) Get(filePath string) (string, error) {
file, err := c.fs.Read(filePath, nil)
if err != nil {
return "", err
}
if file.Type != "plaintext" {
return "", errors.New("todo")
}
fileData := webfilesystem.PlainTextFileData{}
_, err = c.fs.Read(filePath, &fileData)
if err != nil {
return "", err
}
return fileData.Data, nil
}
func (c *Cat) PublicRoutes(route *gin.RouterGroup) {
route.GET("get", func(ctx *gin.Context) {
path := ctx.Query("path")
if path == "" {
ctx.String(http.StatusBadRequest, "TODO") //TODO json error struct
return
}
data, err := c.Get(path)
if err != nil {
ctx.Status(http.StatusInternalServerError)
return
}
mode := ctx.Query("mode")
switch mode {
case "json":
ctx.JSON(http.StatusOK, data)
default:
ctx.String(http.StatusOK, "plaintext", data)
}
})
}