util.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/coreos/etcd/web"
  6. "io"
  7. "io/ioutil"
  8. "net/http"
  9. "os"
  10. )
  11. //--------------------------------------
  12. // Web Helper
  13. //--------------------------------------
  14. func webHelper() {
  15. storeMsg = make(chan string)
  16. for {
  17. web.Hub().Send(<-storeMsg)
  18. }
  19. }
  20. //--------------------------------------
  21. // HTTP Utilities
  22. //--------------------------------------
  23. func decodeJsonRequest(req *http.Request, data interface{}) error {
  24. decoder := json.NewDecoder(req.Body)
  25. if err := decoder.Decode(&data); err != nil && err != io.EOF {
  26. logger.Println("Malformed json request: %v", err)
  27. return fmt.Errorf("Malformed json request: %v", err)
  28. }
  29. return nil
  30. }
  31. func encodeJsonResponse(w http.ResponseWriter, status int, data interface{}) {
  32. w.Header().Set("Content-Type", "application/json")
  33. w.WriteHeader(status)
  34. if data != nil {
  35. encoder := json.NewEncoder(w)
  36. encoder.Encode(data)
  37. }
  38. }
  39. func Post(t *transHandler, path string, body io.Reader) (*http.Response, error) {
  40. if t.client != nil {
  41. resp, err := t.client.Post("https://"+path, "application/json", body)
  42. return resp, err
  43. } else {
  44. resp, err := http.Post("http://"+path, "application/json", body)
  45. return resp, err
  46. }
  47. }
  48. func Get(t *transHandler, path string) (*http.Response, error) {
  49. if t.client != nil {
  50. resp, err := t.client.Get("https://" + path)
  51. return resp, err
  52. } else {
  53. resp, err := http.Get("http://" + path)
  54. return resp, err
  55. }
  56. }
  57. func leaderClient() string {
  58. resp, _ := Get(&serverTransHandler, server.Leader()+"/client")
  59. if resp != nil {
  60. body, _ := ioutil.ReadAll(resp.Body)
  61. resp.Body.Close()
  62. return string(body)
  63. }
  64. return ""
  65. }
  66. //--------------------------------------
  67. // Log
  68. //--------------------------------------
  69. func debug(msg string, v ...interface{}) {
  70. if verbose {
  71. logger.Printf("DEBUG "+msg+"\n", v...)
  72. }
  73. }
  74. func info(msg string, v ...interface{}) {
  75. logger.Printf("INFO "+msg+"\n", v...)
  76. }
  77. func warn(msg string, v ...interface{}) {
  78. logger.Printf("Alpaca Server: WARN "+msg+"\n", v...)
  79. }
  80. func fatal(msg string, v ...interface{}) {
  81. logger.Printf("FATAL "+msg+"\n", v...)
  82. os.Exit(1)
  83. }