Last active
April 18, 2016 04:53
-
-
Save zentrope/d93463d03705d072ff7fb7d2fddd6873 to your computer and use it in GitHub Desktop.
ping web
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"io" | |
"log" | |
"net/http" | |
"os" | |
"os/signal" | |
) | |
// These have to be upper case if we want to marshal with json. | |
type Service struct { | |
Name string `json:"name"` | |
Status string `json:"status"` | |
} | |
type Status struct { | |
Summary string `json:"summary"` | |
Services []Service `json:"services"` | |
} | |
func findStatus() Status { | |
return Status{ | |
Summary: "Partial", | |
Services: []Service{ | |
Service{"Foo", "Ok"}, | |
Service{"Bar", "Ok"}, | |
Service{"Baz", "Down"}}} | |
} | |
func jsonWrite(d interface{}) string { | |
b, err := json.MarshalIndent(d, "", " ") | |
if err != nil { | |
panic(err) | |
} | |
return string(b) | |
} | |
func pingHandler(w http.ResponseWriter, r *http.Request) { | |
io.WriteString(w, "Ok") | |
} | |
func statusHandler(w http.ResponseWriter, r *http.Request) { | |
b := jsonWrite(findStatus()) | |
w.Header().Set("Content-Type", "application/json; charset=utf-8") | |
w.WriteHeader(200) | |
io.WriteString(w, b) | |
} | |
func start() { | |
log.Println("Starting web app.") | |
log.Fatal(http.ListenAndServe(":8080", nil)) | |
} | |
func lock() { | |
log.Println("Setting up signal listener.") | |
var sigChan = make(chan os.Signal, 1) | |
signal.Notify(sigChan, os.Interrupt) | |
whatSig := <-sigChan | |
log.Printf("System signal: `%s`.\n", whatSig) | |
} | |
func main() { | |
log.Println("Hello Ping Web Application") | |
http.HandleFunc("/ping", pingHandler) | |
http.HandleFunc("/status", statusHandler) | |
go start() | |
log.Println("Locking...") | |
lock() | |
log.Println("System halt.") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment