Skip to content

Instantly share code, notes, and snippets.

@skaji
Last active February 29, 2024 18:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skaji/1e1b0ed889f705385a2f881d8815ac71 to your computer and use it in GitHub Desktop.
Save skaji/1e1b0ed889f705385a2f881d8815ac71 to your computer and use it in GitHub Desktop.
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"sync"
"syscall"
)
type status struct {
i int
mu sync.Mutex
}
func (s *status) Set(i int) {
s.mu.Lock()
defer s.mu.Unlock()
s.i = i
}
func (s *status) Get() int {
s.mu.Lock()
defer s.mu.Unlock()
return s.i
}
func main() {
hostname := os.Getenv("HOSTNAME")
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, hostname, "OK")
})
healthStatusCode := &status{i: 200}
mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
s := r.URL.Query().Get("status")
i := 0
if s == "200" {
i = 200
} else if s == "404" {
i = 404
}
if i != 0 {
healthStatusCode.Set(i)
}
fmt.Fprintln(w, hostname, "healthStatusCode = ", healthStatusCode.Get())
return
}
w.WriteHeader(healthStatusCode.Get())
fmt.Fprintln(w, hostname, "healthStatusCode = ", healthStatusCode.Get())
})
healthContainerStatusCode := &status{i: 200}
mux.HandleFunc("/health/container", func(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
s := r.URL.Query().Get("status")
i := 0
if s == "200" {
i = 200
} else if s == "404" {
i = 404
}
if i != 0 {
healthContainerStatusCode.Set(i)
}
fmt.Fprintln(w, hostname, "healthContainerStatusCode = ", healthContainerStatusCode.Get())
return
}
w.WriteHeader(healthContainerStatusCode.Get())
fmt.Fprintln(w, hostname, "healthContainerStatusCode = ", healthContainerStatusCode.Get())
})
server := &http.Server{Addr: ":8080", Handler: mux}
done := make(chan struct{})
go func() {
sig := make(chan os.Signal)
signal.Notify(sig, syscall.SIGTERM, syscall.SIGINT)
<-sig
if err := server.Shutdown(context.Background()); err != nil {
log.Printf("HTTP server Shutdown: %v", err)
}
close(done)
}()
if err := server.ListenAndServe(); err != http.ErrServerClosed {
log.Printf("HTTP server ListenAndServe: %v", err)
}
<-done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment