-
-
Save kenjox/63500b4879cb055527a32a300541f14a to your computer and use it in GitHub Desktop.
Testing Http Handlers in GO
This file contains hidden or 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" | |
"testing" | |
"net/http/httptest" | |
) | |
func TestHealthCheckHandler(t *testing.T) { | |
// Create a request to pass to our handler. We don't have any query parameters for now, so we'll | |
// pass 'nil' as the third parameter. | |
req, err := http.NewRequest("GET", "/health-check", nil) | |
if err != nil { | |
t.Fatal(err) | |
} | |
// We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response. | |
rr := httptest.NewRecorder() | |
handler := http.HandlerFunc(HealthCheckHandler) | |
// Our handlers satisfy http.Handler, so we can call their ServeHTTP method | |
// directly and pass in our Request and ResponseRecorder. | |
handler.ServeHTTP(rr, req) | |
// Check the status code is what we expect. | |
if status := rr.Code; status != http.StatusOK { | |
t.Errorf("handler returned wrong status code: got %v want %v", | |
status, http.StatusOK) | |
} | |
// Check the response body is what we expect. | |
expected := `{"alive": true}` | |
if rr.Body.String() != expected { | |
t.Errorf("handler returned unexpected body: got %v want %v", | |
rr.Body.String(), expected) | |
} | |
} |
This file contains hidden or 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" | |
"io" | |
) | |
func HealthCheckHandler(w http.ResponseWriter, r *http.Request) { | |
w.WriteHeader(http.StatusOK) | |
w.Header().Set("Content-Type", "application/json") | |
io.WriteString(w, `{"alive": true}`) | |
} | |
func main() { | |
http.HandleFunc("/health-check", HealthCheckHandler) | |
http.ListenAndServe(":8080", nil) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment