Cleanup code

This changes variable names that were abbreviations, uses more constants
from the net/http package and improves the json decoding / encoding.
This commit is contained in:
Felix Auringer
2021-04-27 08:47:11 +02:00
parent 78668ad430
commit 712d0e6420
4 changed files with 17 additions and 14 deletions

View File

@ -1,8 +1,11 @@
package api
import "github.com/gorilla/mux"
import (
"github.com/gorilla/mux"
"net/http"
)
// NewRouter returns an HTTP handler (net.Handler) which can then
// NewRouter returns an HTTP handler (http.Handler) which can then
// be used by the net/http package to serve the api of our API.
// We use gorilla/mux because it is more convenient than net/http,
// e.g. when extracting path parameters.
@ -11,7 +14,7 @@ func NewRouter() *mux.Router {
// this can later be restricted to a specific host with
// `router.Host(...)` and to HTTPS with `router.Schemes("https")`
v1 := router.PathPrefix("/api/v1").Subrouter()
v1.HandleFunc("/health", Health).Methods("GET")
v1.HandleFunc("/health", Health).Methods(http.MethodGet)
return v1
}

View File

@ -6,14 +6,14 @@ import (
"net/http"
)
// Health sends the response that the API works. If it
// it is able to do so, it is obviously correct.
// Health tries to respond that the server is alive.
// If it is not, the response won't reach the client.
func Health(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
response, err := json.Marshal(Message{"I'm alive!"})
if err != nil {
log.Printf("Error formatting the health route: %v\n", err)
log.Printf("JSON marshal error in health route: %v\n", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
if _, err := w.Write(response); err != nil {

View File

@ -9,15 +9,15 @@ import (
)
func TestHealthRoute(t *testing.T) {
req, err := http.NewRequest("GET", "/health", nil)
request, err := http.NewRequest(http.MethodGet, "/health", nil)
if err != nil {
t.Fatal(err)
}
rec := httptest.NewRecorder()
http.HandlerFunc(Health).ServeHTTP(rec, req)
res := &Message{}
_ = json.NewDecoder(rec.Body).Decode(res)
recorder := httptest.NewRecorder()
http.HandlerFunc(Health).ServeHTTP(recorder, request)
result := Message{}
_ = json.Unmarshal(recorder.Body.Bytes(), &result)
assert.Equal(t, http.StatusOK, rec.Code)
assert.Equal(t, "I'm alive!", res.Msg)
assert.Equal(t, http.StatusOK, recorder.Code)
assert.Equal(t, "I'm alive!", result.Message)
}

View File

@ -1,5 +1,5 @@
package api
type Message struct {
Msg string `json:"msg"`
Message string `json:"msg"`
}