util.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. trimmed := strings.Split(s, sep)
  34. for i := range trimmed {
  35. trimmed[i] = strings.TrimSpace(trimmed[i])
  36. }
  37. return trimmed
  38. }