khenaidoo | ab1f7bd | 2019-11-14 14:00:27 -0500 | [diff] [blame] | 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 | |
| 15 | // Copyright 2015 The Go Authors. All rights reserved. |
| 16 | // Use of this source code is governed by a BSD-style |
| 17 | // license that can be found in the LICENSE file. |
| 18 | |
| 19 | // Package httputil provides HTTP utility functions. |
| 20 | package httputil |
| 21 | |
| 22 | import ( |
| 23 | "io" |
| 24 | "io/ioutil" |
| 25 | "net" |
| 26 | "net/http" |
| 27 | ) |
| 28 | |
| 29 | // GracefulClose drains http.Response.Body until it hits EOF |
| 30 | // and closes it. This prevents TCP/TLS connections from closing, |
| 31 | // therefore available for reuse. |
| 32 | // Borrowed from golang/net/context/ctxhttp/cancelreq.go. |
| 33 | func GracefulClose(resp *http.Response) { |
| 34 | io.Copy(ioutil.Discard, resp.Body) |
| 35 | resp.Body.Close() |
| 36 | } |
| 37 | |
| 38 | // GetHostname returns the hostname from request Host field. |
| 39 | // It returns empty string, if Host field contains invalid |
| 40 | // value (e.g. "localhost:::" with too many colons). |
| 41 | func GetHostname(req *http.Request) string { |
| 42 | if req == nil { |
| 43 | return "" |
| 44 | } |
| 45 | h, _, err := net.SplitHostPort(req.Host) |
| 46 | if err != nil { |
| 47 | return req.Host |
| 48 | } |
| 49 | return h |
| 50 | } |