Add basic /status endpoint

Also add test for this endpoint
This commit is contained in:
Marc Di Luzio 2020-05-29 17:56:26 +01:00
parent 5377e42e71
commit 4a0a91a1f1
3 changed files with 57 additions and 9 deletions

12
main.go
View file

@ -1,23 +1,17 @@
package main
import (
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
)
func main() {
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/", HandleRoot)
// Create a new router
router := NewRouter()
// Listen and serve the http requests
if err := http.ListenAndServe(":8080", router); err != nil {
log.Fatal(err)
}
}
func HandleRoot(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello World")
}

32
router.go Normal file
View file

@ -0,0 +1,32 @@
package main
import (
"encoding/json"
"net/http"
"github.com/gorilla/mux"
)
func NewRouter() (router *mux.Router) {
// Create a new router
router = mux.NewRouter().StrictSlash(true)
// Set up the handlers
router.HandleFunc("/status", HandleStatus)
return
}
// RouterStatus is a struct that contains information on the status of the server
type RouterStatus struct {
Ready bool `json:"ready"`
}
// HandleStatus handles HTTP requests to the /status endpoint
func HandleStatus(w http.ResponseWriter, r *http.Request) {
var status = RouterStatus{
Ready: true,
}
json.NewEncoder(w).Encode(status)
}

22
router_test.go Normal file
View file

@ -0,0 +1,22 @@
package main
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
)
func TestHandleStatus(t *testing.T) {
request, _ := http.NewRequest(http.MethodGet, "/status", nil)
response := httptest.NewRecorder()
HandleStatus(response, request)
var status RouterStatus
json.NewDecoder(response.Body).Decode(&status)
if status.Ready != true {
t.Errorf("got false for /status")
}
}