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.

81 lines
1.9 KiB

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