http.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright 2020 guylewin, guy@lewin.co.il
  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. package util
  15. import (
  16. "net"
  17. "net/http"
  18. "strings"
  19. )
  20. func OkResponse() *http.Response {
  21. header := make(http.Header)
  22. res := &http.Response{
  23. Status: "OK",
  24. StatusCode: 200,
  25. Proto: "HTTP/1.1",
  26. ProtoMajor: 1,
  27. ProtoMinor: 1,
  28. Header: header,
  29. }
  30. return res
  31. }
  32. // TODO: use "CanonicalHost" func to replace all "GetHostFromAddr" func.
  33. func GetHostFromAddr(addr string) (host string) {
  34. strs := strings.Split(addr, ":")
  35. if len(strs) > 1 {
  36. host = strs[0]
  37. } else {
  38. host = addr
  39. }
  40. return
  41. }
  42. // canonicalHost strips port from host if present and returns the canonicalized
  43. // host name.
  44. func CanonicalHost(host string) (string, error) {
  45. var err error
  46. host = strings.ToLower(host)
  47. if hasPort(host) {
  48. host, _, err = net.SplitHostPort(host)
  49. if err != nil {
  50. return "", err
  51. }
  52. }
  53. if strings.HasSuffix(host, ".") {
  54. // Strip trailing dot from fully qualified domain names.
  55. host = host[:len(host)-1]
  56. }
  57. return host, nil
  58. }
  59. // hasPort reports whether host contains a port number. host may be a host
  60. // name, an IPv4 or an IPv6 address.
  61. func hasPort(host string) bool {
  62. colons := strings.Count(host, ":")
  63. if colons == 0 {
  64. return false
  65. }
  66. if colons == 1 {
  67. return true
  68. }
  69. return host[0] == '[' && strings.Contains(host, "]:")
  70. }