| // |
| 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 | package http |
| 16 |
| 17 | import ( |
| 18 | "encoding/base64" |
| 19 | "net" |
| 20 | "net/http" |
| 21 | "strings" |
| 22 | ) |
| 23 |
| 24 | func OkResponse() *http.Response { |
| 25 | header := make(http.Header) |
| 26 |
| 27 | res := &http.Response{ |
| 28 | Status: "OK", |
| 29 | StatusCode: 200, |
| 30 | Proto: "HTTP/1.1", |
| 31 | ProtoMajor: 1, |
| 32 | ProtoMinor: 1, |
| 33 | Header: header, |
| 34 | } |
| 35 | return res |
| 36 | } |
| 37 |
| 38 | func ProxyUnauthorizedResponse() *http.Response { |
| 39 | header := make(http.Header) |
| 40 | header.Set("Proxy-Authenticate", `Basic realm="Restricted"`) |
| 41 | res := &http.Response{ |
| 42 | Status: "Proxy Authentication Required", |
| 43 | StatusCode: 407, |
| 44 | Proto: "HTTP/1.1", |
| 45 | ProtoMajor: 1, |
| 46 | ProtoMinor: 1, |
| 47 | Header: header, |
| 48 | } |
| 49 | return res |
| 50 | } |
| 51 |
| 52 | // canonicalHost strips port from host if present and returns the canonicalized |
| 53 | // host name. |
| 54 | func CanonicalHost(host string) (string, error) { |
| 55 | var err error |
| 56 | host = strings.ToLower(host) |
| 57 | if hasPort(host) { |
| 58 | host, _, err = net.SplitHostPort(host) |
| 59 | if err != nil { |
| 60 | return "", err |
| 61 | } |
| 62 | } |
| 63 | // Strip trailing dot from fully qualified domain names. |
| 64 | host = strings.TrimSuffix(host, ".") |
| 65 | return host, nil |
| 66 | } |
| 67 |
| 68 | // hasPort reports whether host contains a port number. host may be a host |
| 69 | // name, an IPv4 or an IPv6 address. |
| 70 | func hasPort(host string) bool { |
| 71 | colons := strings.Count(host, ":") |
| 72 | if colons == 0 { |
| 73 | return false |
| 74 | } |
| 75 | if colons == 1 { |
| 76 | return true |
| 77 | } |
| 78 | return host[0] == '[' && strings.Contains(host, "]:") |
| 79 | } |
| 80 |
| 81 | func ParseBasicAuth(auth string) (username, password string, ok bool) { |
| 82 | const prefix = "Basic " |
| 83 | // Case insensitive prefix match. See Issue 22736. |
| 84 | if len(auth) < len(prefix) || !strings.EqualFold(auth[:len(prefix)], prefix) { |
| 85 | return |
| 86 | } |
| 87 | c, err := base64.StdEncoding.DecodeString(auth[len(prefix):]) |
| 88 | if err != nil { |
| 89 | return |
| 90 | } |
| 91 | cs := string(c) |
| 92 | before, after, found := strings.Cut(cs, ":") |
| 93 | if !found { |
| 94 | return |
| 95 | } |
| 96 | return before, after, true |
| 97 | } |
| 98 |
| 99 | func BasicAuth(username, passwd string) string { |
| 100 | auth := username + ":" + passwd |
| 101 | return "Basic " + base64.StdEncoding.EncodeToString([]byte(auth)) |
| 102 | } |