package main import ( "fmt" "net/http" "os" "strconv" "strings" "forge.arimelody.space/ari/indir/log" "forge.arimelody.space/ari/indir/web" ) func main() { if len(os.Args) < 2 { printHelp() } host := "127.0.0.1" port := 8080 root := "/" filesDir := "" i := 1 for { if i >= len(os.Args) { break } switch os.Args[i] { case "-h": fallthrough case "--help": printHelp() case "--host": if i + 1 >= len(os.Args) { fmt.Fprintf(os.Stderr, "fatal: --host argument cannot be empty\n") os.Exit(1) } i++ host = os.Args[i] case "--port": if i + 1 >= len(os.Args) { fmt.Fprintf(os.Stderr, "fatal: --port argument cannot be empty\n") os.Exit(1) } i++ var err error port, err = strconv.Atoi(os.Args[i]) if err != nil { fmt.Fprintf(os.Stderr, "fatal: failed to parse port %s: %v\n", os.Args[i], err) os.Exit(1) } case "--root": if i + 1 >= len(os.Args) { fmt.Fprintf(os.Stderr, "fatal: --root argument cannot be empty\n") os.Exit(1) } i++ root = os.Args[i] if !strings.HasPrefix(root, "/") { root = "/" + root } if !strings.HasSuffix(root, "/") { root += "/" } default: if len(filesDir) > 0 { fmt.Fprintf(os.Stderr, "unsupported argument: %s\n", os.Args[i]) os.Exit(1) } filesDir = os.Args[i] } i++ } if len(filesDir) == 0 { filesDir = "." } ignoredFiles := []string{ ".", ".DS_Store", } fmt.Printf("Now hosting \"%s\" at http://%s:%d", filesDir, host, port) if root != "/" { fmt.Printf("%s", root) } fmt.Println(".") app := web.AppState{ Root: root, FilesDir: filesDir, IgnoredFiles: ignoredFiles, } http.ListenAndServe( fmt.Sprintf("%s:%d", host, port), log.HTTPLog(web.Handler(&app)), ) } func printHelp() { fmt.Printf( `indir [--host address] [--port port] [--root http_root] directory --help shows this help message --host address hosts on the specified address --port port hosts on the specified port --root http_root hosts on the specified subdirectory, i.e. `+"`/files/`\n", ) os.Exit(0) }