title: Go - passing generic struct to function
body: <p>Considering the following code, which is responding to GET '/venues/:id':</p>
  
  <pre><code>func venueShow(w http.ResponseWriter, req *http.Request) {
  
    // get ID from params
    vars := mux.Vars(req)
    id := vars["id"]
  
    // initialise new struct
    var venue Venue
  
    // select by id and scan into struct
    db.First(&amp;venue, id).Scan(&amp;venue)
  
    // turn it to json
    response := structToJSON(&amp;venue)
  
    // write headers and provide response
    w.Header().Set("Content-Type", "application/json")
    w.Write(response)
  }
  </code></pre>
  
  <p>and:</p>
  
  <pre><code>func structToJSON (s interface{}) (response []byte) {
    // turn it into pretty-ish json
    response, err := json.MarshalIndent(&amp;s, "", "  ")
    if err != nil {
     return []byte("Venue does not exist")
    }
    // return the json as the reponse
    return response
  }
  </code></pre>
  
  <p>My structToJSON function is taking an empty interface as the argument, because I want to pass various different structs to the function and have them spewed out as JSON.</p>
  
  <p>However, it doesn't strike me as very safe. If anything satisfies an empty interface, I could pass whatever I wanted into that function, and all sorts of errors might happen when json.Marshal tries to do it's business. This (I suppose) would be caught by the compiler rather than at runtime, but is there a safer way?</p>
  
  <p>I could duplicate the structToJSON method for each different type of Struct/Model that I pass to it, but that's not very DRY.</p>
  
  <p>Thanks</p>