Guest User

Untitled

a guest
Jul 15th, 2015
351
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.35 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "text/template"
  5. "net/http"
  6. "runtime"
  7. )
  8.  
  9. var templates map[string]*template.Template
  10.  
  11. // Load templates on program initialisation
  12. func init() {
  13. runtime.GOMAXPROCS(runtime.NumCPU())
  14.  
  15. if templates == nil {
  16. templates = make(map[string]*template.Template)
  17. }
  18.  
  19. templates["index.html"] = template.Must(template.ParseFiles("index.html"))
  20. }
  21.  
  22. func handler(w http.ResponseWriter, r *http.Request) {
  23. type Post struct {
  24. Id int
  25. Title, Content string
  26. }
  27.  
  28. Posts := make([]*Post, 100) // A slice of pointers
  29.  
  30. // Fill posts
  31. for i := range Posts {
  32. // Initialize pointers: just copies the address of the created struct value
  33. Posts[i]= &Post{i, "Sample Title", "Lorem Ipsum Dolor Sit Amet"}
  34. }
  35.  
  36. type Page struct {
  37. Title, Subtitle string
  38. Posts []*Post // "Just" a slice type (it's a descriptor)
  39. }
  40.  
  41. // Create a page, only the Posts slice descriptor is copied
  42. p := Page{"Index Page of My Super Blog", "A blog about everything", Posts}
  43.  
  44. tmpl := templates["index.html"]
  45.  
  46. // Only pass the address of p
  47. // Although since Page.Posts is now just a slice, passing by value would also be OK
  48. tmpl.Execute(w, &p)
  49. }
  50.  
  51. func main() {
  52. http.HandleFunc("/", handler)
  53. http.ListenAndServe(":8888", nil)
  54. }
Advertisement
Add Comment
Please, Sign In to add comment