github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/tools/cmd/godoc/blog.go (about)

     1  // Copyright 2013 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  package main
     6  
     7  import (
     8  	"fmt"
     9  	"go/build"
    10  	"log"
    11  	"net/http"
    12  	"os"
    13  	"path/filepath"
    14  	"runtime"
    15  	"strings"
    16  	"sync"
    17  
    18  	"golang.org/x/tools/blog"
    19  	"golang.org/x/tools/godoc/redirect"
    20  )
    21  
    22  const (
    23  	blogRepo = "golang.org/x/blog"
    24  	blogURL  = "http://blog.golang.org/"
    25  	blogPath = "/blog/"
    26  )
    27  
    28  var (
    29  	blogServer   http.Handler // set by blogInit
    30  	blogInitOnce sync.Once
    31  	playEnabled  bool
    32  )
    33  
    34  func init() {
    35  	// Initialize blog only when first accessed.
    36  	http.HandleFunc(blogPath, func(w http.ResponseWriter, r *http.Request) {
    37  		blogInitOnce.Do(blogInit)
    38  		blogServer.ServeHTTP(w, r)
    39  	})
    40  }
    41  
    42  func blogInit() {
    43  	// Binary distributions will include the blog content in "/blog".
    44  	root := filepath.Join(runtime.GOROOT(), "blog")
    45  
    46  	// Prefer content from go.blog repository if present.
    47  	if pkg, err := build.Import(blogRepo, "", build.FindOnly); err == nil {
    48  		root = pkg.Dir
    49  	}
    50  
    51  	// If content is not available fall back to redirect.
    52  	if fi, err := os.Stat(root); err != nil || !fi.IsDir() {
    53  		fmt.Fprintf(os.Stderr, "Blog content not available locally. "+
    54  			"To install, run \n\tgo get %v\n", blogRepo)
    55  		blogServer = http.HandlerFunc(blogRedirectHandler)
    56  		return
    57  	}
    58  
    59  	s, err := blog.NewServer(blog.Config{
    60  		BaseURL:      blogPath,
    61  		BasePath:     strings.TrimSuffix(blogPath, "/"),
    62  		ContentPath:  filepath.Join(root, "content"),
    63  		TemplatePath: filepath.Join(root, "template"),
    64  		HomeArticles: 5,
    65  		PlayEnabled:  playEnabled,
    66  	})
    67  	if err != nil {
    68  		log.Fatal(err)
    69  	}
    70  	blogServer = s
    71  }
    72  
    73  func blogRedirectHandler(w http.ResponseWriter, r *http.Request) {
    74  	if r.URL.Path == blogPath {
    75  		http.Redirect(w, r, blogURL, http.StatusFound)
    76  		return
    77  	}
    78  	blogPrefixHandler.ServeHTTP(w, r)
    79  }
    80  
    81  var blogPrefixHandler = redirect.PrefixHandler(blogPath, blogURL)