List the updated files without using go build again

Issue

I am just starting with Go. I’ve a question regarding gorilla/mux.

I am trying to list out the files inside a directory; and the response will be sent back from GET request to list the files.
Now, when I create a new file inside directory; the GET request doesn’t list the new file.
I understand I need to run go build again. Can I do it without building it again ?

type Images struct {
    Image     string `json:"image"`
    Path      string `json:"path"`
    Timestamp string `json:"timestamp"`
    Labels    string `json:"labels"`
    Version   string `json:"version"`
}


var images []Images


func getImages(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(images)
}

func main() {
    r := mux.NewRouter()

    files, err := ioutil.ReadDir(os.Args[1])

    if err != nil {
        log.Fatal(err)
    }

    for _, file := range files {
        images = append(images, Images{Image: file.Name(), Path: os.Args[1]})
    }
    fmt.Println(images)

    // Route handles & endpoints
    r.HandleFunc("/images", getImages).Methods("GET")

    log.Fatal(http.ListenAndServe(":8080", r))
}

Solution

The application reads the list of files at startup. To update the list of files, you must restart the application. You do not need to run go build to get an updated list of files.

To get an up-to-date list of files on every request, read the list of files in the request handler function:

func getImages(w http.ResponseWriter, r *http.Request) {
    files, err := ioutil.ReadDir(os.Args[1])
    if err != nil {
        http.Error(w, "Internal server error", 500)
        return
    }

    var images []Images
    for _, file := range files {
        images = append(images, Images{Image: file.Name(), Path: os.Args[1]})
    }

    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(images)
}

Remove the corresponding code from main() and the images package-level variable.

Answered By – Zombo

Answer Checked By – Terry (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.