81 lines
1.8 KiB
Go
81 lines
1.8 KiB
Go
package server
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"io/fs"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
|
|
"git.zervo.org/zervo/fileserver"
|
|
"git.zervo.org/zervo/fileserver/internal/config"
|
|
"git.zervo.org/zervo/fileserver/internal/server/controllers"
|
|
"github.com/kataras/iris/v12"
|
|
"github.com/kataras/iris/v12/view"
|
|
)
|
|
|
|
// Start starts the server.
|
|
func Start(cfg *config.ServerConfig) error {
|
|
app := iris.New()
|
|
|
|
templates, err := fs.Sub(fileserver.TemplateFS, "templates")
|
|
if err != nil {
|
|
return errors.New("fs.Sub operation on TemplateFS")
|
|
}
|
|
|
|
templater := view.HTML(templates, ".html").Layout("layouts/main.html")
|
|
app.RegisterView(templater)
|
|
|
|
// Register core routes
|
|
app.Get("/", index)
|
|
app.Get("/favicon.ico", favicon)
|
|
|
|
// Register controller routes
|
|
controllers.DirectoriesRoute(app, cfg)
|
|
|
|
app.Get("/aaa", func(ctx iris.Context) {
|
|
files, err := os.ReadDir("test")
|
|
if err != nil {
|
|
ctx.StatusCode(http.StatusInternalServerError)
|
|
ctx.WriteString("Could not read directory")
|
|
return
|
|
}
|
|
|
|
var filenames []string
|
|
for _, f := range files {
|
|
if !f.IsDir() {
|
|
filenames = append(filenames, f.Name())
|
|
}
|
|
}
|
|
|
|
fmt.Printf("Files: %v\n", filenames)
|
|
|
|
ctx.ViewData("Files", filenames)
|
|
ctx.View("index.html")
|
|
})
|
|
|
|
app.Get("/download/{filename:string}", func(ctx iris.Context) {
|
|
filename := ctx.Params().Get("filename")
|
|
filePath := filepath.Join("test", filename)
|
|
ctx.SendFile(filePath, filename)
|
|
})
|
|
|
|
return app.Listen(":" + fmt.Sprint(cfg.WebPort))
|
|
}
|
|
|
|
// index redirects request from '/' to '/directories'.
|
|
func index(ctx iris.Context) {
|
|
ctx.Redirect("/directories")
|
|
}
|
|
|
|
// favicon returns favicon data upon request.
|
|
func favicon(ctx iris.Context) {
|
|
data, err := fileserver.StaticFS.ReadFile("static/favicon.ico")
|
|
if err != nil {
|
|
ctx.StatusCode(http.StatusNotFound)
|
|
return
|
|
}
|
|
ctx.ContentType("image/x-icon")
|
|
ctx.Write(data)
|
|
}
|