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.
5 // godoc: Go Documentation Server
9 // http://godoc/ redirect to /pkg/
10 // http://godoc/src/ serve files from $GOROOT/src; .go gets pretty-printed
11 // http://godoc/cmd/ serve documentation about commands
12 // http://godoc/pkg/ serve documentation about packages
13 // (idea is if you say import "compress/zlib", you go to
14 // http://godoc/pkg/compress/zlib)
24 _ "expvar" // to serve /debug/vars
31 _ "net/http/pprof" // to serve /debug/pprof/*
41 "golang.org/x/tools/godoc"
42 "golang.org/x/tools/godoc/analysis"
43 "golang.org/x/tools/godoc/static"
44 "golang.org/x/tools/godoc/vfs"
45 "golang.org/x/tools/godoc/vfs/gatefs"
46 "golang.org/x/tools/godoc/vfs/mapfs"
47 "golang.org/x/tools/godoc/vfs/zipfs"
48 "golang.org/x/tools/internal/gocommand"
49 "golang.org/x/xerrors"
52 const defaultAddr = "localhost:6060" // default webserver address
55 // file system to serve
56 // (with e.g.: zip -r go.zip $GOROOT -i \*.go -i \*.html -i \*.css -i \*.js -i \*.txt -i \*.c -i \*.h -i \*.s -i \*.png -i \*.jpg -i \*.sh -i favicon.ico)
57 zipfile = flag.String("zip", "", "zip file providing the file system to serve; disabled if empty")
60 writeIndex = flag.Bool("write_index", false, "write index to a file; the file name must be specified with -index_files")
62 analysisFlag = flag.String("analysis", "", `comma-separated list of analyses to perform when in GOPATH mode (supported: type, pointer). See https://golang.org/lib/godoc/analysis/help.html`)
65 httpAddr = flag.String("http", defaultAddr, "HTTP service address")
68 urlFlag = flag.String("url", "", "print HTML for named URL")
70 verbose = flag.Bool("v", false, "verbose mode")
73 // TODO(gri) consider the invariant that goroot always end in '/'
74 goroot = flag.String("goroot", findGOROOT(), "Go root directory")
77 showTimestamps = flag.Bool("timestamps", false, "show timestamps with directory listings")
78 templateDir = flag.String("templates", "", "load templates/JS/CSS from disk in this directory")
79 showPlayground = flag.Bool("play", false, "enable playground")
80 declLinks = flag.Bool("links", true, "link identifiers to their declarations")
83 indexEnabled = flag.Bool("index", false, "enable search index")
84 indexFiles = flag.String("index_files", "", "glob pattern specifying index files; if not empty, the index is read from these files in sorted order")
85 indexInterval = flag.Duration("index_interval", 0, "interval of indexing; 0 for default (5m), negative to only index once at startup")
86 maxResults = flag.Int("maxresults", 10000, "maximum number of full text search results shown")
87 indexThrottle = flag.Float64("index_throttle", 0.75, "index throttle value; 0.0 = no time allocated, 1.0 = full throttle")
90 notesRx = flag.String("notes", "BUG", "regular expression matching note markers to show")
93 // An httpResponseRecorder is an http.ResponseWriter
94 type httpResponseRecorder struct {
100 func (w *httpResponseRecorder) Header() http.Header { return w.header }
101 func (w *httpResponseRecorder) Write(b []byte) (int, error) { return w.body.Write(b) }
102 func (w *httpResponseRecorder) WriteHeader(code int) { w.code = code }
105 fmt.Fprintf(os.Stderr, "usage: godoc -http="+defaultAddr+"\n")
110 func loggingHandler(h http.Handler) http.Handler {
111 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
112 log.Printf("%s\t%s", req.RemoteAddr, req.URL)
117 func handleURLFlag() {
118 // Try up to 10 fetches, following redirects.
120 for i := 0; i < 10; i++ {
122 u, err := url.Parse(urlstr)
126 req := &http.Request{
130 // Invoke default HTTP handler to serve request
131 // to our buffering httpWriter.
132 w := &httpResponseRecorder{code: 200, header: make(http.Header), body: new(bytes.Buffer)}
133 http.DefaultServeMux.ServeHTTP(w, req)
135 // Return data, error, or follow redirect.
138 os.Stdout.Write(w.body.Bytes())
140 case 301, 302, 303, 307: // redirect
141 redirect := w.header.Get("Location")
143 log.Fatalf("HTTP %d without Location header", w.code)
147 log.Fatalf("HTTP error %d", w.code)
150 log.Fatalf("too many redirects")
153 func initCorpus(corpus *godoc.Corpus) {
166 fmt.Fprintln(os.Stderr, `Unexpected arguments. Use "go doc" for command-line help output instead. For example, "go doc fmt.Printf".`)
169 if *httpAddr == "" && *urlFlag == "" && !*writeIndex {
170 fmt.Fprintln(os.Stderr, "At least one of -http, -url, or -write_index must be set to a non-zero value.")
174 // Set the resolved goroot.
177 fsGate := make(chan bool, 20)
179 // Determine file system to use.
181 // use file system of underlying OS
182 rootfs := gatefs.New(vfs.OS(*goroot), fsGate)
183 fs.Bind("/", rootfs, "/", vfs.BindReplace)
185 // use file system specified via .zip file (path separator must be '/')
186 rc, err := zip.OpenReader(*zipfile)
188 log.Fatalf("%s: %s\n", *zipfile, err)
190 defer rc.Close() // be nice (e.g., -writeIndex mode)
191 fs.Bind("/", zipfs.New(rc, *zipfile), *goroot, vfs.BindReplace)
193 if *templateDir != "" {
194 fs.Bind("/lib/godoc", vfs.OS(*templateDir), "/", vfs.BindBefore)
196 fs.Bind("/lib/godoc", mapfs.New(static.Files), "/", vfs.BindReplace)
199 // Get the GOMOD value, use it to determine if godoc is being invoked in module mode.
200 goModFile, err := goMod()
202 fmt.Fprintf(os.Stderr, "failed to determine go env GOMOD value: %v", err)
203 goModFile = "" // Fall back to GOPATH mode.
207 fmt.Printf("using module mode; GOMOD=%s\n", goModFile)
209 if *analysisFlag != "" {
210 fmt.Fprintln(os.Stderr, "The -analysis flag is supported only in GOPATH mode at this time.")
211 fmt.Fprintln(os.Stderr, "See https://golang.org/issue/34473.")
215 // Detect whether to use vendor mode or not.
216 mainMod, vendorEnabled, err := gocommand.VendorEnabled(context.Background(), gocommand.Invocation{}, &gocommand.Runner{})
218 fmt.Fprintf(os.Stderr, "failed to determine if vendoring is enabled: %v", err)
222 // Bind the root directory of the main module.
223 fs.Bind(path.Join("/src", mainMod.Path), gatefs.New(vfs.OS(mainMod.Dir), fsGate), "/", vfs.BindAfter)
225 // Bind the vendor directory.
227 // Note that in module mode, vendor directories in locations
228 // other than the main module's root directory are ignored.
229 // See https://golang.org/ref/mod#vendoring.
230 vendorDir := filepath.Join(mainMod.Dir, "vendor")
231 fs.Bind("/src", gatefs.New(vfs.OS(vendorDir), fsGate), "/", vfs.BindAfter)
234 // Try to download dependencies that are not in the module cache in order to
235 // to show their documentation.
236 // This may fail if module downloading is disallowed (GOPROXY=off) or due to
237 // limited connectivity, in which case we print errors to stderr and show
238 // documentation only for packages that are available.
239 fillModuleCache(os.Stderr, goModFile)
241 // Determine modules in the build list.
242 mods, err := buildList(goModFile)
244 fmt.Fprintf(os.Stderr, "failed to determine the build list of the main module: %v", err)
248 // Bind module trees into Go root.
249 for _, m := range mods {
251 // Module is not available in the module cache, skip it.
254 dst := path.Join("/src", m.Path)
255 fs.Bind(dst, gatefs.New(vfs.OS(m.Dir), fsGate), "/", vfs.BindAfter)
259 fmt.Println("using GOPATH mode")
261 // Bind $GOPATH trees into Go root.
262 for _, p := range filepath.SplitList(build.Default.GOPATH) {
263 fs.Bind("/src", gatefs.New(vfs.OS(p), fsGate), "/src", vfs.BindAfter)
267 var typeAnalysis, pointerAnalysis bool
268 if *analysisFlag != "" {
269 for _, a := range strings.Split(*analysisFlag, ",") {
274 pointerAnalysis = true
276 log.Fatalf("unknown analysis: %s", a)
281 var corpus *godoc.Corpus
283 corpus = godoc.NewCorpus(moduleFS{fs})
285 corpus = godoc.NewCorpus(fs)
287 corpus.Verbose = *verbose
288 corpus.MaxResults = *maxResults
289 corpus.IndexEnabled = *indexEnabled
290 if *maxResults == 0 {
291 corpus.IndexFullText = false
293 corpus.IndexFiles = *indexFiles
294 corpus.IndexDirectory = func(dir string) bool {
295 return dir != "/pkg" && !strings.HasPrefix(dir, "/pkg/")
297 corpus.IndexThrottle = *indexThrottle
298 corpus.IndexInterval = *indexInterval
299 if *writeIndex || *urlFlag != "" {
300 corpus.IndexThrottle = 1.0
301 corpus.IndexEnabled = true
304 go initCorpus(corpus)
307 // Initialize the version info before readTemplates, which saves
308 // the map value in a method value.
309 corpus.InitVersionInfo()
311 pres = godoc.NewPresentation(corpus)
312 pres.ShowTimestamps = *showTimestamps
313 pres.ShowPlayground = *showPlayground
314 pres.DeclLinks = *declLinks
316 pres.NotesRx = regexp.MustCompile(*notesRx)
320 registerHandlers(pres)
323 // Write search index and exit.
324 if *indexFiles == "" {
325 log.Fatal("no index file specified")
328 log.Println("initialize file systems")
329 *verbose = true // want to see what happens
333 log.Println("writing index file", *indexFiles)
334 f, err := os.Create(*indexFiles)
338 index, _ := corpus.CurrentIndex()
339 _, err = index.WriteTo(f)
348 // Print content that would be served at the URL *urlFlag.
354 var handler http.Handler = http.DefaultServeMux
356 log.Printf("Go Documentation Server")
357 log.Printf("version = %s", runtime.Version())
358 log.Printf("address = %s", *httpAddr)
359 log.Printf("goroot = %s", *goroot)
362 log.Print("search index disabled")
363 case *maxResults > 0:
364 log.Printf("full text index enabled (maxresults = %d)", *maxResults)
366 log.Print("identifier search index enabled")
369 handler = loggingHandler(handler)
372 // Initialize search index.
374 go corpus.RunIndexer()
377 // Start type/pointer analysis.
378 if typeAnalysis || pointerAnalysis {
379 go analysis.Run(pointerAnalysis, &corpus.Analysis)
382 // Start http server.
384 log.Println("starting HTTP server")
386 if err := http.ListenAndServe(*httpAddr, handler); err != nil {
387 log.Fatalf("ListenAndServe %s: %v", *httpAddr, err)
391 // goMod returns the go env GOMOD value in the current directory
392 // by invoking the go command.
394 // GOMOD is documented at https://golang.org/cmd/go/#hdr-Environment_variables:
396 // The absolute path to the go.mod of the main module,
397 // or the empty string if not using modules.
399 func goMod() (string, error) {
400 out, err := exec.Command("go", "env", "-json", "GOMOD").Output()
401 if ee := (*exec.ExitError)(nil); xerrors.As(err, &ee) {
402 return "", fmt.Errorf("go command exited unsuccessfully: %v\n%s", ee.ProcessState.String(), ee.Stderr)
403 } else if err != nil {
409 err = json.Unmarshal(out, &env)
413 return env.GoMod, nil
416 // fillModuleCache does a best-effort attempt to fill the module cache
417 // with all dependencies of the main module in the current directory
418 // by invoking the go command. Module download logs are streamed to w.
419 // If there are any problems encountered, they are also written to w.
420 // It should only be used in module mode, when vendor mode isn't on.
422 // See https://golang.org/cmd/go/#hdr-Download_modules_to_local_cache.
423 func fillModuleCache(w io.Writer, goMod string) {
424 if goMod == os.DevNull {
425 // No module requirements, nothing to do.
429 cmd := exec.Command("go", "mod", "download", "-json")
434 if ee := (*exec.ExitError)(nil); xerrors.As(err, &ee) && ee.ExitCode() == 1 {
435 // Exit code 1 from this command means there were some
436 // non-empty Error values in the output. Print them to w.
437 fmt.Fprintf(w, "documentation for some packages is not shown:\n")
438 for dec := json.NewDecoder(&out); ; {
440 Path string // Module path.
441 Version string // Module version.
442 Error string // Error loading module.
444 err := dec.Decode(&m)
447 } else if err != nil {
448 fmt.Fprintf(w, "error decoding JSON object from go mod download -json: %v\n", err)
454 fmt.Fprintf(w, "\tmodule %s@%s is not in the module cache and there was a problem downloading it: %s\n", m.Path, m.Version, m.Error)
456 } else if err != nil {
457 fmt.Fprintf(w, "there was a problem filling module cache: %v\n", err)
462 Path string // Module path.
463 Dir string // Directory holding files for this module, if any.
466 // buildList determines the build list in the current directory
467 // by invoking the go command. It should only be used in module mode,
468 // when vendor mode isn't on.
470 // See https://golang.org/cmd/go/#hdr-The_main_module_and_the_build_list.
471 func buildList(goMod string) ([]mod, error) {
472 if goMod == os.DevNull {
477 out, err := exec.Command("go", "list", "-m", "-json", "all").Output()
478 if ee := (*exec.ExitError)(nil); xerrors.As(err, &ee) {
479 return nil, fmt.Errorf("go command exited unsuccessfully: %v\n%s", ee.ProcessState.String(), ee.Stderr)
480 } else if err != nil {
484 for dec := json.NewDecoder(bytes.NewReader(out)); ; {
486 err := dec.Decode(&m)
489 } else if err != nil {
492 mods = append(mods, m)
497 // moduleFS is a vfs.FileSystem wrapper used when godoc is running
498 // in module mode. It's needed so that packages inside modules are
499 // considered to be third party.
501 // It overrides the RootType method of the underlying filesystem
502 // and implements it using a heuristic based on the import path.
503 // If the first element of the import path does not contain a dot,
504 // that package is considered to be inside GOROOT. If it contains
505 // a dot, then that package is considered to be third party.
507 // TODO(dmitshur): The RootType abstraction works well when GOPATH
508 // workspaces are bound at their roots, but scales poorly in the
509 // general case. It should be replaced by a more direct solution
510 // for determining whether a package is third party or not.
512 type moduleFS struct{ vfs.FileSystem }
514 func (moduleFS) RootType(path string) vfs.RootType {
515 if !strings.HasPrefix(path, "/src/") {
518 domain := path[len("/src/"):]
519 if i := strings.Index(domain, "/"); i >= 0 {
522 if !strings.Contains(domain, ".") {
523 // No dot in the first element of import path
524 // suggests this is a package in GOROOT.
525 return vfs.RootTypeGoRoot
527 // A dot in the first element of import path
528 // suggests this is a third party package.
529 return vfs.RootTypeGoPath
532 func (fs moduleFS) String() string { return "module(" + fs.FileSystem.String() + ")" }