Adds support for listing directories as well as getting file contents

This commit is contained in:
sloumdrone 2019-10-05 13:10:09 -07:00
parent 484fb77aa3
commit ee9fc8332c
2 changed files with 40 additions and 0 deletions

View File

@ -4,18 +4,57 @@ import (
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"os" "os"
"strings"
) )
func Open(address string) (string, error) { func Open(address string) (string, error) {
if !pathExists(address) {
return "", fmt.Errorf("Invalid system path: %s", address)
}
file, err := os.Open(address) file, err := os.Open(address)
if err != nil { if err != nil {
return "", fmt.Errorf("Unable to open file: %s", address) return "", fmt.Errorf("Unable to open file: %s", address)
} }
defer file.Close() defer file.Close()
if pathIsDir(address) {
fileList, err := file.Readdirnames(0)
if err != nil {
return "", fmt.Errorf("Unable to read from directory: %s", address)
}
var out strings.Builder
out.WriteString(fmt.Sprintf("Current directory: %s\n\n", address))
for _, obj := range fileList {
out.WriteString(obj)
out.WriteString("\n")
}
return out.String(), nil
}
bytes, err := ioutil.ReadAll(file) bytes, err := ioutil.ReadAll(file)
if err != nil { if err != nil {
return "", fmt.Errorf("Unable to read file: %s", address) return "", fmt.Errorf("Unable to read file: %s", address)
} }
return string(bytes), nil return string(bytes), nil
} }
func pathExists(p string) bool {
exists := true
if _, err := os.Stat(p); os.IsNotExist(err) {
exists = false
}
return exists
}
func pathIsDir(p string) bool {
info, err := os.Stat(p)
if err != nil {
return false
}
return info.IsDir()
}

1
url.go
View File

@ -130,3 +130,4 @@ func MakeUrl(u string) (Url, error) {
return out, nil return out, nil
} }