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