Skip to content

Commit

Permalink
Created Ping API
Browse files Browse the repository at this point in the history
  • Loading branch information
peterramaldes committed Apr 6, 2022
1 parent dd21bc9 commit 01d9c7e
Show file tree
Hide file tree
Showing 5 changed files with 58 additions and 0 deletions.
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/peterramaldes/billgo

go 1.18
7 changes: 7 additions & 0 deletions handlers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package main

import "net/http"

func handlers(mux *http.ServeMux) {
mux.Handle("/ping", &pingHandler{})
}
8 changes: 8 additions & 0 deletions http.go
Original file line number Diff line number Diff line change
@@ -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"}`))
}
11 changes: 11 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package main

import (
"net/http"
)

func main() {
mux := http.NewServeMux()
handlers(mux)
http.ListenAndServe(":3000", mux)
}
29 changes: 29 additions & 0 deletions ping.go
Original file line number Diff line number Diff line change
@@ -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"}`))
}

0 comments on commit 01d9c7e

Please sign in to comment.