Skip to content

Instantly share code, notes, and snippets.

@Blquinn
Created September 5, 2019 19:37
Show Gist options
  • Save Blquinn/9710fc6412fd7f14abb95dd0aadcc5a6 to your computer and use it in GitHub Desktop.
Save Blquinn/9710fc6412fd7f14abb95dd0aadcc5a6 to your computer and use it in GitHub Desktop.
Hacking variadics to have optional arguments
package main
import (
"net/http"
"encoding/json"
)
// Using variadic (hack) to default the response code to 200
func sendJSON(w http.ResponseWriter, v interface{}, status ...int) {
st := http.StatusOK
if len(status) > 0 {
st = status[0]
}
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(st)
if err := json.NewEncoder(w).Encode(v); err != nil {
log.Errorf("Failed to send response: %s", err)
}
}
func handler(w http.ResponseWriter, r *http.Request) {
if true {
sendJSON(w, "something went wrong", http.StatusInternatServerError)
}
sendJSON(w, "Hello world") // Returns 200
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment