Search code examples
functiongostructredundancy

How can I reduce redundant code of duplicate function in Golang?


I have a Rest API application to list all json data to browser. as long as I have more modules my code is more redundant. and complex.

func UserList(w http.ResponseWriter, r *http.Request) {
    list := []models.User{}
    db.Find(&list)
    json.NewEncoder(w).Encode(list)
}

func ProductList(w http.ResponseWriter, r *http.Request) {
    list := []models.Product{}
    db.Find(&list)
    json.NewEncoder(w).Encode(list)
}

func OrderList(w http.ResponseWriter, r *http.Request) {
    list := []models.Order{}
    db.Find(&list)
    json.NewEncoder(w).Encode(list)
}

Is there any better solution to make this code into just one function Example

func List(w http.ResponseWriter, r *http.Request) {
    list := ??? List of struct here ???
    db.Find(&list)
    json.NewEncoder(w).Encode(list)
}

Solution

  • you can do something like this:

    func List(list interface{}, w http.ResponseWriter, r *http.Request,) {
        db.Find(list)
        json.NewEncoder(w).Encode(list)
    }