Search code examples
restgenericsgo

How to write a generic handler in Go?


I need to create a HTTP Handler for a REST API.

This REST API have many different objects that are stored in a database (MongoDB in my case).

Currently, I need to write one handler per action per object.

I would like to find a way like it's possible with Generics to write a generic handler that could handle a specific action but for any kind of object (As basically it's just CRUD in most of the case)

How can I do this ?

Here is examples of Handlers I would like to transform into a generic one :

func IngredientIndex(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json; charset=UTF-8")
    db := r.Context().Value("Database").(*mgo.Database)
    ingredients := []data.Ingredient{}
    err := db.C("ingredients").Find(bson.M{}).All(&ingredients)
    if err != nil {
        panic(err)
    }
    json.NewEncoder(w).Encode(ingredients)
}

func IngredientGet(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json; charset=UTF-8")
    vars := mux.Vars(r)
    logger := r.Context().Value("Logger").(zap.Logger)
    db := r.Context().Value("Database").(*mgo.Database)
    ingredient := data.Ingredient{}
    err := db.C("ingredients").Find(bson.M{"_id": bson.ObjectIdHex(vars["id"])}).One(&ingredient)
    if err != nil {
        w.WriteHeader(404)
        logger.Info("Fail to find entity", zap.Error(err))
    } else {
        json.NewEncoder(w).Encode(ingredient)
    }
}

Basically I would need a handler like this (This is my tentative that doesn't work) :

func ObjectIndex(collection string, container interface{}) func(http.ResponseWriter, *http.Request) {
    return func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "application/json; charset=UTF-8")
        db := r.Context().Value("Database").(*mgo.Database)
        objects := container
        err := db.C(collection).Find(bson.M{}).All(&objects)
        if err != nil {
            panic(err)
        }
        json.NewEncoder(w).Encode(objects)
    }

How can I do that ?


Solution

  • Use the reflect package to create a new container on each invocation:

    func ObjectIndex(collection string, container interface{}) func(http.ResponseWriter, *http.Request) {
      t := reflect.TypeOf(container)
      return func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "application/json; charset=UTF-8")
        db := r.Context().Value("Database").(*mgo.Database)
        objects := reflect.New(t).Interface()
        err := db.C(collection).Find(bson.M{}).All(objects)
        if err != nil {
            panic(err)
        }
        json.NewEncoder(w).Encode(objects)
    }
    

    Call it like this:

    h := ObjectIndex("ingredients", data.Ingredient{})
    

    assuming that data.Indgredient is a slice type.