mardi 27 octobre 2015

Create slice of pointers using reflection in Go

I've seen a few examples of reflection around this topic, but I can't find anything that solves this issue. It feels a little convoluted, but the alternative is a massive amount of repetition so I thought I'd give it a try.

I have a function that returns a function (handler). The wrapping function passes in an instance of a struct. I need the inner function to create a slice of pointers to that struct type:

func createCollectionHandler(app *appSession, record interface{}, name string) func(res http.ResponseWriter, req *http.Request) {
    return func(res http.ResponseWriter, req *http.Request) {
        res.Header().Set("Content-Type", "application/json")

        // This line needs to be dynamic:
        var result []*Person

        err := meddler.QueryAll(app.MysqlDB, &result, "select * from "+name)
        if err != nil {
            log.Fatal(err)
        }
        json, err := json.MarshalIndent(result, "", " ")
        if err != nil {
            log.Println(err)
        }
        res.Write([]byte(json))
        return
    }
}





Aucun commentaire:

Enregistrer un commentaire