Created
September 5, 2019 19:37
-
-
Save Blquinn/9710fc6412fd7f14abb95dd0aadcc5a6 to your computer and use it in GitHub Desktop.
Hacking variadics to have optional arguments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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