httputil.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. // Copyright 2018 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // Copyright 2015 The Go Authors. All rights reserved.
  15. // Use of this source code is governed by a BSD-style
  16. // license that can be found in the LICENSE file.
  17. // Package httputil provides HTTP utility functions.
  18. package httputil
  19. import (
  20. "io"
  21. "io/ioutil"
  22. "net"
  23. "net/http"
  24. )
  25. // GracefulClose drains http.Response.Body until it hits EOF
  26. // and closes it. This prevents TCP/TLS connections from closing,
  27. // therefore available for reuse.
  28. // Borrowed from golang/net/context/ctxhttp/cancelreq.go.
  29. func GracefulClose(resp *http.Response) {
  30. io.Copy(ioutil.Discard, resp.Body)
  31. resp.Body.Close()
  32. }
  33. // GetHostname returns the hostname from request Host field.
  34. // It returns empty string, if Host field contains invalid
  35. // value (e.g. "localhost:::" with too many colons).
  36. func GetHostname(req *http.Request) string {
  37. if req == nil {
  38. return ""
  39. }
  40. h, _, err := net.SplitHostPort(req.Host)
  41. if err != nil {
  42. return req.Host
  43. }
  44. return h
  45. }