0

Code:

    files, err := ioutil.ReadDir(".")
    elements := make(map[string]interface{})
    for _, file := range files {
        elements["name"] = file.Name()
        elements["directory"] = file.IsDir()
        elements["size"] = file.Size()
    }
    ctxt.JSON(http.StatusOK, elements)

Here I'm getting a response with only last file details.
How can I create a slice of objects, that means I want all files details in the response.

3
  • 1
    You should try using a concrete struct, it is a much better programming experience then having to deal with maps of empty interfaces... That said, in each iteration you need to create a map and aggregate those maps into a slice, that way you get all the files details. (play.golang.com/p/xjDrWwvtDZC) Commented Nov 11, 2019 at 7:01
  • 1
    Work through the Tour of Go once more for basic language constructs. Commented Nov 11, 2019 at 7:10
  • @mkopriva. Its working fine for me Commented Nov 11, 2019 at 7:13

2 Answers 2

2

Something like this:

files, err := ioutil.ReadDir(".")
elements := []map[string]interface{}{}
for _, file := range files {
    elements = append(elements, map[string]interface{}{
        "name":      file.Name(),
        "directory": file.IsDir(),
        "size":      file.Size()})
}
ctxt.JSON(http.StatusOK, elements)
Sign up to request clarification or add additional context in comments.

1 Comment

I also agree with @mkopriva about using struct, but that's up to you.
0

instead of append, you can create the array with size

package main
import (
    "fmt"
    "io/ioutil"
)

func main() {
    files, _ := ioutil.ReadDir(".")
    elements := make([]map[string]interface{}, len(files))
    for i, file := range files {

        e := map[string]interface{}{
            "name":      file.Name(),
            "directory": file.IsDir(),
            "size":      file.Size(),
        }

        elements[i] = e
    }

    for i, e := range elements {
        fmt.Println(i, e)
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.