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.

72 lines
1.5 KiB

  1. // Copyright 2009 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. // +build !appengine
  5. package main
  6. import (
  7. "errors"
  8. "flag"
  9. "io"
  10. "log"
  11. "net/http"
  12. "net/url"
  13. "os"
  14. )
  15. func handleRemoteSearch() {
  16. // Command-line queries.
  17. for i := 0; i < flag.NArg(); i++ {
  18. res, err := remoteSearch(flag.Arg(i))
  19. if err != nil {
  20. log.Fatalf("remoteSearch: %s", err)
  21. }
  22. io.Copy(os.Stdout, res.Body)
  23. }
  24. return
  25. }
  26. // remoteSearchURL returns the search URL for a given query as needed by
  27. // remoteSearch. If html is set, an html result is requested; otherwise
  28. // the result is in textual form.
  29. // Adjust this function as necessary if modeNames or FormValue parameters
  30. // change.
  31. func remoteSearchURL(query string, html bool) string {
  32. s := "/search?m=text&q="
  33. if html {
  34. s = "/search?q="
  35. }
  36. return s + url.QueryEscape(query)
  37. }
  38. func remoteSearch(query string) (res *http.Response, err error) {
  39. // list of addresses to try
  40. var addrs []string
  41. if *serverAddr != "" {
  42. // explicit server address - only try this one
  43. addrs = []string{*serverAddr}
  44. } else {
  45. addrs = []string{
  46. defaultAddr,
  47. "golang.org",
  48. }
  49. }
  50. // remote search
  51. search := remoteSearchURL(query, *html)
  52. for _, addr := range addrs {
  53. url := "http://" + addr + search
  54. res, err = http.Get(url)
  55. if err == nil && res.StatusCode == http.StatusOK {
  56. break
  57. }
  58. }
  59. if err == nil && res.StatusCode != http.StatusOK {
  60. err = errors.New(res.Status)
  61. }
  62. return
  63. }