Advertisement
Guest User

Untitled

a guest
Jul 14th, 2015
277
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "text/template"
  5. "net/http"
  6. "runtime"
  7. "fmt"
  8. "io"
  9. )
  10.  
  11. var templates map[string]*template.Template
  12.  
  13. type Post struct {
  14. Id int
  15. Title, Content string
  16. }
  17.  
  18. type Page struct {
  19. Title, Subtitle string
  20. Posts []*Post // "Just" a slice type (it's a descriptor)
  21. }
  22.  
  23. // Load templates on program initialisation
  24. func init() {
  25. runtime.GOMAXPROCS(runtime.NumCPU())
  26.  
  27. if templates == nil {
  28. templates = make(map[string]*template.Template)
  29. }
  30.  
  31. templates["index.html"] = template.Must(template.ParseFiles("index.html"))
  32. }
  33.  
  34. func dodo() Page {
  35. Posts := make([]*Post, 100) // A slice of pointers
  36.  
  37. for i := range Posts {
  38. // Initialize pointers: just copies the address of the created struct value
  39. Posts[i]= &Post{i, "Sample Title", "Lorem Ipsum Dolor Sit Amet"}
  40. }
  41.  
  42. // Create a page, only the Posts slice descriptor is copied
  43. p := Page{"Index Page of My Super Blog", "A blog about everything", Posts}
  44.  
  45. return p
  46. }
  47.  
  48. func handler(w http.ResponseWriter, r *http.Request) {
  49. tmpl := templates["index.html"]
  50.  
  51. var x Page
  52. go func() {
  53. x = dodo()
  54. }()
  55.  
  56. // Only pass the address of p
  57. // Although since Page.Posts is now just a slice, passing by value would also be OK
  58. tmpl.Execute(w, x)
  59. }
  60.  
  61. func loader(w http.ResponseWriter, r *http.Request) {
  62. io.WriteString(w, "loaderio-8e7b651418140f598d78797c25483f89")
  63. }
  64.  
  65. func main() {
  66. fmt.Println("Using cores:", MaxParallelism())
  67.  
  68. fs := http.FileServer(http.Dir("assets"))
  69. http.Handle("/assets/", http.StripPrefix("/assets/", fs))
  70.  
  71. http.HandleFunc("/loaderio-8e7b651418140f598d78797c25483f89.txt", loader)
  72.  
  73. http.HandleFunc("/", handler)
  74. http.ListenAndServe(":7777", nil)
  75. }
  76.  
  77. func MaxParallelism() int {
  78. maxProcs := runtime.GOMAXPROCS(0)
  79. numCPU := runtime.NumCPU()
  80. if maxProcs < numCPU {
  81. return maxProcs
  82. }
  83. return numCPU
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement