http_ctl.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "log"
  6. "net/http"
  7. "os"
  8. fractal "git.lattuga.net/blallo/gotools/formatting"
  9. "git.lattuga.net/boyska/circolog"
  10. "github.com/gorilla/mux"
  11. )
  12. func setupHTTPCtl(hub circolog.Hub, verbose bool) *mux.Router {
  13. m := mux.NewRouter()
  14. m.HandleFunc("/pause/toggle", togglePause(hub, verbose)).Methods("POST")
  15. m.HandleFunc("/logs/clear", clearQueue(hub, verbose)).Methods("POST")
  16. m.HandleFunc("/help", printHelp(verbose)).Methods("GET")
  17. m.HandleFunc("/echo", echo(verbose)).Methods("GET")
  18. return m
  19. }
  20. func togglePause(hub circolog.Hub, verbose bool) http.HandlerFunc {
  21. return func(w http.ResponseWriter, r *http.Request) {
  22. if verbose {
  23. log.Printf("[%s] %s - toggled pause", r.Method, r.RemoteAddr)
  24. }
  25. hub.Commands <- circolog.HubFullCommand{Command: circolog.CommandPauseToggle}
  26. resp := <-hub.Responses
  27. active := resp.Value.(bool)
  28. w.Header().Set("content-type", "application/json")
  29. enc := json.NewEncoder(w)
  30. enc.Encode(map[string]interface{}{"paused": !active})
  31. }
  32. }
  33. func clearQueue(hub circolog.Hub, verbose bool) http.HandlerFunc {
  34. return func(w http.ResponseWriter, r *http.Request) {
  35. if verbose {
  36. log.Printf("[%s] %s - cleared queue", r.Method, r.RemoteAddr)
  37. }
  38. hub.Commands <- circolog.HubFullCommand{Command: circolog.CommandClear}
  39. resp := <-hub.Responses
  40. success := resp.Value.(bool)
  41. w.Header().Set("content-type", "application/json")
  42. enc := json.NewEncoder(w)
  43. enc.Encode(map[string]interface{}{"success": success})
  44. }
  45. }
  46. func printHelp(verbose bool) http.HandlerFunc {
  47. return func(w http.ResponseWriter, r *http.Request) {
  48. if verbose {
  49. log.Printf("[%s] %s - asked for help", r.Method, r.RemoteAddr)
  50. }
  51. w.Header().Set("content-type", "application/json")
  52. enc := json.NewEncoder(w)
  53. var pathsWithDocs = map[string]string{
  54. "/pause/toggle": "Toggle the server from pause state (not listening)",
  55. "/logs/clear": "Wipe the buffer from all the messages",
  56. "/help": "This help",
  57. "/echo": "Answers to heartbeat",
  58. }
  59. fractal.EncodeJSON(pathsWithDocs, enc)
  60. if verbose {
  61. errEnc := json.NewEncoder(os.Stderr)
  62. fractal.EncodeJSON(pathsWithDocs, errEnc)
  63. }
  64. }
  65. }
  66. func echo(verbose bool) http.HandlerFunc {
  67. return func(w http.ResponseWriter, r *http.Request) {
  68. log.Println("Echo")
  69. if verbose {
  70. log.Printf("[%s] %s - asked for echo", r.Method, r.RemoteAddr)
  71. }
  72. w.Header().Set("content-type", "text/plain")
  73. fmt.Fprintln(w, "I am on!")
  74. }
  75. }