Improve directory handling

This commit is contained in:
James Mills 2016-09-22 23:50:44 +10:00
parent 44c294287d
commit 65cbf62f8a
No known key found for this signature in database
GPG Key ID: AC4C014F1440EBD6

View File

@ -210,6 +210,17 @@ func (i *Item) parse(line []byte) error {
return nil return nil
} }
func (i *Item) isDirectoryLike() bool {
switch i.Type {
case DIRECTORY:
return true
case INDEXSEARCH:
return true
default:
return false
}
}
// Directory representes a Gopher Menu of Items // Directory representes a Gopher Menu of Items
type Directory []Item type Directory []Item
@ -290,22 +301,20 @@ func Get(uri string) (*Response, error) {
i := Item{Type: Type, Selector: Selector, Host: host, Port: port} i := Item{Type: Type, Selector: Selector, Host: host, Port: port}
res := Response{Type: i.Type} res := Response{Type: i.Type}
if i.Type == ItemType(DIRECTORY) { if i.isDirectoryLike() {
d, err := i.FetchDirectory() d, err := i.FetchDirectory()
if err != nil { if err != nil {
return nil, err return nil, err
} }
res.Dir = d res.Dir = d
} else if i.Type == ItemType(FILE) { } else {
reader, err := i.FetchFile() reader, err := i.FetchFile()
if err != nil { if err != nil {
return nil, err return nil, err
} }
res.Body = reader res.Body = reader
} else {
return nil, fmt.Errorf("unsupported type: %s", i.Type)
} }
return &res, nil return &res, nil
@ -319,10 +328,6 @@ func (i *Item) FetchFile() (io.Reader, error) {
return nil, errors.New("cannot fetch a directory as a file") return nil, errors.New("cannot fetch a directory as a file")
} }
if i.Type != FILE {
return nil, errors.New("non-plaintext encodings not supported")
}
conn, err := net.Dial("tcp", i.Host+":"+strconv.Itoa(i.Port)) conn, err := net.Dial("tcp", i.Host+":"+strconv.Itoa(i.Port))
if err != nil { if err != nil {
return nil, err return nil, err
@ -340,7 +345,7 @@ func (i *Item) FetchFile() (io.Reader, error) {
// FetchDirectory fetches directory information, not data. // FetchDirectory fetches directory information, not data.
// Calling this on an Item whose type is not DIRECTORY will return an error. // Calling this on an Item whose type is not DIRECTORY will return an error.
func (i *Item) FetchDirectory() (Directory, error) { func (i *Item) FetchDirectory() (Directory, error) {
if i.Type != DIRECTORY { if !i.isDirectoryLike() {
return nil, errors.New("cannot fetch a file as a directory") return nil, errors.New("cannot fetch a file as a directory")
} }