blob: 41758138a47d9f3944324020cc62d47cf617d9cf [file] [log] [blame]
Abhay Kumar40252eb2025-10-13 13:25:53 +00001// 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.
20package httputil
21
22import (
23 "io"
24 "net"
25 "net/http"
26)
27
28// GracefulClose drains http.Response.Body until it hits EOF
29// and closes it. This prevents TCP/TLS connections from closing,
30// therefore available for reuse.
31// Borrowed from golang/net/context/ctxhttp/cancelreq.go.
32func GracefulClose(resp *http.Response) {
33 io.Copy(io.Discard, resp.Body)
34 resp.Body.Close()
35}
36
37// GetHostname returns the hostname from request Host field.
38// It returns empty string, if Host field contains invalid
39// value (e.g. "localhost:::" with too many colons).
40func GetHostname(req *http.Request) string {
41 if req == nil {
42 return ""
43 }
44 h, _, err := net.SplitHostPort(req.Host)
45 if err != nil {
46 return req.Host
47 }
48 return h
49}