12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- package main
- import (
- "encoding/json"
- "fmt"
- "log"
- "net/http"
- "os"
- fractal "git.lattuga.net/blallo/gotools/formatting"
- "git.lattuga.net/boyska/circolog"
- "github.com/gorilla/mux"
- )
- func setupHTTPCtl(hub circolog.Hub, verbose bool) *mux.Router {
- m := mux.NewRouter()
- m.HandleFunc("/pause/toggle", togglePause(hub, verbose)).Methods("POST")
- m.HandleFunc("/logs/clear", clearQueue(hub, verbose)).Methods("POST")
- m.HandleFunc("/help", printHelp(verbose)).Methods("GET")
- m.HandleFunc("/echo", echo(verbose)).Methods("GET")
- return m
- }
- func togglePause(hub circolog.Hub, verbose bool) http.HandlerFunc {
- return func(w http.ResponseWriter, r *http.Request) {
- if verbose {
- log.Printf("[%s] %s - toggled pause", r.Method, r.RemoteAddr)
- }
- hub.Commands <- circolog.HubFullCommand{Command: circolog.CommandPauseToggle}
- resp := <-hub.Responses
- active := resp.Value.(bool)
- w.Header().Set("content-type", "application/json")
- enc := json.NewEncoder(w)
- enc.Encode(map[string]interface{}{"paused": !active})
- }
- }
- func clearQueue(hub circolog.Hub, verbose bool) http.HandlerFunc {
- return func(w http.ResponseWriter, r *http.Request) {
- if verbose {
- log.Printf("[%s] %s - cleared queue", r.Method, r.RemoteAddr)
- }
- hub.Commands <- circolog.HubFullCommand{Command: circolog.CommandClear}
- resp := <-hub.Responses
- success := resp.Value.(bool)
- w.Header().Set("content-type", "application/json")
- enc := json.NewEncoder(w)
- enc.Encode(map[string]interface{}{"success": success})
- }
- }
- func printHelp(verbose bool) http.HandlerFunc {
- return func(w http.ResponseWriter, r *http.Request) {
- if verbose {
- log.Printf("[%s] %s - asked for help", r.Method, r.RemoteAddr)
- }
- w.Header().Set("content-type", "application/json")
- enc := json.NewEncoder(w)
- var pathsWithDocs = map[string]string{
- "/pause/toggle": "Toggle the server from pause state (not listening)",
- "/logs/clear": "Wipe the buffer from all the messages",
- "/help": "This help",
- "/echo": "Answers to heartbeat",
- }
- fractal.EncodeJSON(pathsWithDocs, enc)
- if verbose {
- errEnc := json.NewEncoder(os.Stderr)
- fractal.EncodeJSON(pathsWithDocs, errEnc)
- }
- }
- }
- func echo(verbose bool) http.HandlerFunc {
- return func(w http.ResponseWriter, r *http.Request) {
- log.Println("Echo")
- if verbose {
- log.Printf("[%s] %s - asked for echo", r.Method, r.RemoteAddr)
- }
- w.Header().Set("content-type", "text/plain")
- fmt.Fprintln(w, "I am on!")
- }
- }
|