github.com/jgarto/itcv@v0.0.0-20180826224514-4eea09c1aa0d/_vendor/src/golang.org/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(func() {
    38  			blogInit(r.Host)
    39  		})
    40  		blogServer.ServeHTTP(w, r)
    41  	})
    42  }
    43  
    44  func blogInit(host string) {
    45  	// Binary distributions will include the blog content in "/blog".
    46  	root := filepath.Join(runtime.GOROOT(), "blog")
    47  
    48  	// Prefer content from go.blog repository if present.
    49  	if pkg, err := build.Import(blogRepo, "", build.FindOnly); err == nil {
    50  		root = pkg.Dir
    51  	}
    52  
    53  	// If content is not available fall back to redirect.
    54  	if fi, err := os.Stat(root); err != nil || !fi.IsDir() {
    55  		fmt.Fprintf(os.Stderr, "Blog content not available locally. "+
    56  			"To install, run \n\tgo get %v\n", blogRepo)
    57  		blogServer = http.HandlerFunc(blogRedirectHandler)
    58  		return
    59  	}
    60  
    61  	s, err := blog.NewServer(blog.Config{
    62  		BaseURL:         blogPath,
    63  		BasePath:        strings.TrimSuffix(blogPath, "/"),
    64  		ContentPath:     filepath.Join(root, "content"),
    65  		TemplatePath:    filepath.Join(root, "template"),
    66  		HomeArticles:    5,
    67  		PlayEnabled:     playEnabled,
    68  		ServeLocalLinks: strings.HasPrefix(host, "localhost"),
    69  	})
    70  	if err != nil {
    71  		log.Fatal(err)
    72  	}
    73  	blogServer = s
    74  }
    75  
    76  func blogRedirectHandler(w http.ResponseWriter, r *http.Request) {
    77  	if r.URL.Path == blogPath {
    78  		http.Redirect(w, r, blogURL, http.StatusFound)
    79  		return
    80  	}
    81  	blogPrefixHandler.ServeHTTP(w, r)
    82  }
    83  
    84  var blogPrefixHandler = redirect.PrefixHandler(blogPath, blogURL)