You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

80 lines
2.0 KiB

  1. // Copyright 2012 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package vcs
  5. import (
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "log"
  10. "net/http"
  11. "net/url"
  12. )
  13. // httpClient is the default HTTP client, but a variable so it can be
  14. // changed by tests, without modifying http.DefaultClient.
  15. var httpClient = http.DefaultClient
  16. // httpGET returns the data from an HTTP GET request for the given URL.
  17. func httpGET(url string) ([]byte, error) {
  18. resp, err := httpClient.Get(url)
  19. if err != nil {
  20. return nil, err
  21. }
  22. defer resp.Body.Close()
  23. if resp.StatusCode != 200 {
  24. return nil, fmt.Errorf("%s: %s", url, resp.Status)
  25. }
  26. b, err := ioutil.ReadAll(resp.Body)
  27. if err != nil {
  28. return nil, fmt.Errorf("%s: %v", url, err)
  29. }
  30. return b, nil
  31. }
  32. // httpsOrHTTP returns the body of either the importPath's
  33. // https resource or, if unavailable, the http resource.
  34. func httpsOrHTTP(importPath string) (urlStr string, body io.ReadCloser, err error) {
  35. fetch := func(scheme string) (urlStr string, res *http.Response, err error) {
  36. u, err := url.Parse(scheme + "://" + importPath)
  37. if err != nil {
  38. return "", nil, err
  39. }
  40. u.RawQuery = "go-get=1"
  41. urlStr = u.String()
  42. if Verbose {
  43. log.Printf("Fetching %s", urlStr)
  44. }
  45. res, err = httpClient.Get(urlStr)
  46. return
  47. }
  48. closeBody := func(res *http.Response) {
  49. if res != nil {
  50. res.Body.Close()
  51. }
  52. }
  53. urlStr, res, err := fetch("https")
  54. if err != nil || res.StatusCode != 200 {
  55. if Verbose {
  56. if err != nil {
  57. log.Printf("https fetch failed.")
  58. } else {
  59. log.Printf("ignoring https fetch with status code %d", res.StatusCode)
  60. }
  61. }
  62. closeBody(res)
  63. urlStr, res, err = fetch("http")
  64. }
  65. if err != nil {
  66. closeBody(res)
  67. return "", nil, err
  68. }
  69. // Note: accepting a non-200 OK here, so people can serve a
  70. // meta import in their http 404 page.
  71. if Verbose {
  72. log.Printf("Parsing meta tags from %s (status code %d)", urlStr, res.StatusCode)
  73. }
  74. return urlStr, res.Body, nil
  75. }