Initial backend api

This commit is contained in:
2024-09-25 20:36:09 +02:00
parent 646b683cbb
commit a135f28fd5
9 changed files with 219 additions and 132 deletions

View File

@@ -0,0 +1,36 @@
package api
import (
"encoding/json"
"net/http"
"strings"
"novamd/internal/filesystem"
)
func ListFiles(fs *filesystem.FileSystem) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
files, err := fs.ListFilesRecursively()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(files)
}
}
func GetFileContent(fs *filesystem.FileSystem) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
filePath := strings.TrimPrefix(r.URL.Path, "/api/v1/files/")
content, err := fs.GetFileContent(filePath)
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "text/plain")
w.Write(content)
}
}

View File

@@ -0,0 +1,37 @@
package filesystem
import (
"io/ioutil"
"os"
"path/filepath"
)
type FileSystem struct {
RootDir string
}
func New(rootDir string) *FileSystem {
return &FileSystem{RootDir: rootDir}
}
func (fs *FileSystem) ListFilesRecursively() ([]string, error) {
var files []string
err := filepath.Walk(fs.RootDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
relPath, _ := filepath.Rel(fs.RootDir, path)
files = append(files, relPath)
}
return nil
})
return files, err
}
func (fs *FileSystem) GetFileContent(filePath string) ([]byte, error) {
fullPath := filepath.Join(fs.RootDir, filePath)
return ioutil.ReadFile(fullPath)
}