util.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package server
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "net/url"
  8. "strings"
  9. "github.com/coreos/etcd/log"
  10. )
  11. func decodeJsonRequest(req *http.Request, data interface{}) error {
  12. decoder := json.NewDecoder(req.Body)
  13. if err := decoder.Decode(&data); err != nil && err != io.EOF {
  14. log.Warnf("Malformed json request: %v", err)
  15. return fmt.Errorf("Malformed json request: %v", err)
  16. }
  17. return nil
  18. }
  19. func redirect(hostname string, w http.ResponseWriter, req *http.Request) {
  20. originalURL := req.URL
  21. redirectURL, _ := url.Parse(hostname)
  22. // we need the original path and raw query
  23. redirectURL.Path = originalURL.Path
  24. redirectURL.RawQuery = originalURL.RawQuery
  25. redirectURL.Fragment = originalURL.Fragment
  26. log.Debugf("Redirect to %s", redirectURL.String())
  27. http.Redirect(w, req, redirectURL.String(), http.StatusTemporaryRedirect)
  28. }
  29. // trimsplit slices s into all substrings separated by sep and returns a
  30. // slice of the substrings between the separator with all leading and trailing
  31. // white space removed, as defined by Unicode.
  32. func trimsplit(s, sep string) []string {
  33. raw := strings.Split(s, ",")
  34. trimmed := make([]string, 0)
  35. for _, r := range raw {
  36. trimmed = append(trimmed, strings.TrimSpace(r))
  37. }
  38. return trimmed
  39. }