Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "text/template"
- "net/http"
- "runtime"
- "fmt"
- "io"
- )
- var templates map[string]*template.Template
- type Post struct {
- Id int
- Title, Content string
- }
- type Page struct {
- Title, Subtitle string
- Posts []*Post // "Just" a slice type (it's a descriptor)
- }
- // Load templates on program initialisation
- func init() {
- runtime.GOMAXPROCS(runtime.NumCPU())
- if templates == nil {
- templates = make(map[string]*template.Template)
- }
- templates["index.html"] = template.Must(template.ParseFiles("index.html"))
- }
- func dodo() Page {
- Posts := make([]*Post, 100) // A slice of pointers
- for i := range Posts {
- // Initialize pointers: just copies the address of the created struct value
- Posts[i]= &Post{i, "Sample Title", "Lorem Ipsum Dolor Sit Amet"}
- }
- // Create a page, only the Posts slice descriptor is copied
- p := Page{"Index Page of My Super Blog", "A blog about everything", Posts}
- return p
- }
- func handler(w http.ResponseWriter, r *http.Request) {
- tmpl := templates["index.html"]
- var x Page
- go func() {
- x = dodo()
- }()
- // Only pass the address of p
- // Although since Page.Posts is now just a slice, passing by value would also be OK
- tmpl.Execute(w, x)
- }
- func loader(w http.ResponseWriter, r *http.Request) {
- io.WriteString(w, "loaderio-8e7b651418140f598d78797c25483f89")
- }
- func main() {
- fmt.Println("Using cores:", MaxParallelism())
- fs := http.FileServer(http.Dir("assets"))
- http.Handle("/assets/", http.StripPrefix("/assets/", fs))
- http.HandleFunc("/loaderio-8e7b651418140f598d78797c25483f89.txt", loader)
- http.HandleFunc("/", handler)
- http.ListenAndServe(":7777", nil)
- }
- func MaxParallelism() int {
- maxProcs := runtime.GOMAXPROCS(0)
- numCPU := runtime.NumCPU()
- if maxProcs < numCPU {
- return maxProcs
- }
- return numCPU
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement