From 01d9c7e2b2a26a7605150720a97fb96dc5ae16e0 Mon Sep 17 00:00:00 2001 From: Peter Admilson Ramaldes Date: Wed, 6 Apr 2022 02:53:28 -0300 Subject: [PATCH] Created Ping API --- go.mod | 3 +++ handlers.go | 7 +++++++ http.go | 8 ++++++++ main.go | 11 +++++++++++ ping.go | 29 +++++++++++++++++++++++++++++ 5 files changed, 58 insertions(+) create mode 100644 go.mod create mode 100644 handlers.go create mode 100644 http.go create mode 100644 main.go create mode 100644 ping.go diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..25bb1a7 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module github.com/peterramaldes/billgo + +go 1.18 diff --git a/handlers.go b/handlers.go new file mode 100644 index 0000000..37f0eed --- /dev/null +++ b/handlers.go @@ -0,0 +1,7 @@ +package main + +import "net/http" + +func handlers(mux *http.ServeMux) { + mux.Handle("/ping", &pingHandler{}) +} diff --git a/http.go b/http.go new file mode 100644 index 0000000..580ac0e --- /dev/null +++ b/http.go @@ -0,0 +1,8 @@ +package main + +import "net/http" + +func notFound(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusNotFound) + w.Write([]byte(`{"error": "not found"}`)) +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..44587f1 --- /dev/null +++ b/main.go @@ -0,0 +1,11 @@ +package main + +import ( + "net/http" +) + +func main() { + mux := http.NewServeMux() + handlers(mux) + http.ListenAndServe(":3000", mux) +} diff --git a/ping.go b/ping.go new file mode 100644 index 0000000..9c3f678 --- /dev/null +++ b/ping.go @@ -0,0 +1,29 @@ +package main + +import ( + "net/http" + "regexp" +) + +var ( + pingRe = regexp.MustCompile(`^\/ping*$`) +) + +type pingHandler struct{} + +func (h *pingHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + w.Header().Set("content-type", "application/json") + switch { + case r.Method == http.MethodGet && pingRe.MatchString(r.URL.Path): + h.Ping(w, r) + return + default: + notFound(w, r) + return + } +} + +func (h *pingHandler) Ping(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + w.Write([]byte(`{"status": "alive"}`)) +}