fe5538a315e0 — Dang Hoang Tuan (Tsuki) 1 year, 11 months ago
Massive overhaul to help Robin deal with CLI. Robin now can handle custom directories and custom ports
3 files changed, 54 insertions(+), 26 deletions(-)

M consts.go
M main.go
A => server.go
M consts.go +2 -1
@@ 9,7 9,6 @@ import (
 
 const OK int = http.StatusOK
 const NOT_FOUND int = http.StatusNotFound
-const ACCESSIBLE_DIR string = "/home/firefly/" // Accessible directory
 const HELP = `
 HELP
 ===================================

          
@@ 25,3 24,5 @@ be:
 `
 var spf = fmt.Sprintf
 var sp = fmt.Sprint
+var ACCESSIBLE_DIR string = "./" // Accessible directory
+var PORT int = 1323 // Default port

          
M main.go +11 -25
@@ 1,36 1,22 @@ 
-// main.go - Contains the main stuff
 package main
 
 import (
-	"log"
 	"os"
 
-	"github.com/labstack/echo/v4"
+	"github.com/mkideal/cli"
 )
 
-var currentDir = ACCESSIBLE_DIR; // ACCESSIBLE_DIR from consts.go
-
-// GET /
-// displayFolder and notFound from helper_functions.go
-func index(c echo.Context) error {
-	path := ACCESSIBLE_DIR + c.QueryParam("path")
-	log.Println("path = ", path)
-	fi, err := os.Stat(path)
-	if err != nil {
-		return notFound(c, "File or directory not found")
-	}
-	switch mode := fi.Mode(); {
-	case mode.IsDir():
-		return displayFolder(c, path)
-	case mode.IsRegular():
-		return c.Inline(path, path)
-	}
-
-	return notFound(c, "Unknown error. Please try again.")
+type Flags struct {
+  cli.Helper
+  Port int `cli:"p,port" usage:"Port number (default is 1323)"`
+  Directory string `cli:"d,dir" usage:"Directory to display (default is .)"`
 }
 
 func main() {
-  e := echo.New()
-	e.GET("/", index)
-	e.Logger.Fatal(e.Start(":1323"))
+  os.Exit(cli.Run(new(Flags), func (ctx *cli.Context) error {
+    argv := ctx.Argv().(*Flags)
+    ctx.String("Port=%d, Directory=%s", argv.Port, argv.Directory)
+    serve(argv.Port, argv.Directory)
+    return nil
+  }))
 }

          
A => server.go +41 -0
@@ 0,0 1,41 @@ 
+// main.go - Contains the main stuff
+package main
+
+import (
+	"log"
+	"os"
+
+	"github.com/labstack/echo/v4"
+)
+
+// GET /
+// displayFolder and notFound from helper_functions.go
+func index(c echo.Context) error {
+	path := ACCESSIBLE_DIR + c.QueryParam("path")
+	log.Println("path = ", path)
+	fi, err := os.Stat(path)
+	if err != nil {
+		return notFound(c, "File or directory not found")
+	}
+	switch mode := fi.Mode(); {
+	case mode.IsDir():
+		return displayFolder(c, path)
+	case mode.IsRegular():
+		return c.Inline(path, path)
+	}
+
+	return notFound(c, "Unknown error. Please try again.")
+}
+
+func serve(port int, dir string) {
+	// Processing CLI arguments
+	if port != 0 {
+		PORT = port
+	}
+	if dir != "" {
+		ACCESSIBLE_DIR = dir 
+	}
+  e := echo.New()
+	e.GET("/", index)
+	e.Logger.Fatal(e.Start(spf(":%d", port)))
+}