Attempting to pass data to func(w http.ResponseWriter, r *http.Request)

Viewed 463

I am attempting to create a multilingual site and need to pass additional data to func(w http.ResponseWriter, r *http.Request)

func main() {
defer func() {
    if r := recover(); r != nil {
        fmt.Printf("Recovering from panic, error is: %v \n", r)
    }
}()
    router := mux.NewRouter()

    for _, page := range pages.Pages {
        fmt.Print("page: ")
        fmt.Println(page.Slug)
        http.HandleFunc(page.Slug, func(w http.ResponseWriter, r *http.Request) {
            fmt.Println("http.HandleFunc") //<-never prints
            err := tmpl.ExecuteTemplate(w, page.Template, page)
            if err != nil {
                http.Error(w, err.Error(), http.StatusInternalServerError)
            }
        })
    }


    router.Use(middlewareHeaders)
    var err error
    tmpl, err = template.ParseGlob("views/*")
    if err != nil {
        panic(err.Error())
    }

    router.PathPrefix("/").HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
        http.FileServer(http.Dir("./static/")).ServeHTTP(res, req)
    })

    fmt.Println("Server running on localhost" + pages.Config.Port)

    err = http.ListenAndServe(pages.Config.Port, handlers.CompressHandler(router))
    if err != nil {
        log.Fatal(err)
    }
}

When running to code I get the following console output:

page: /
page: /about
page: /terms
page: /es
page: /sobre
page: /condiciones
Server running on localhost:8081

The code never reaches inside the http.HandleFunc When I make a GET request to http://localhost:8081/ or any of the other paths listed I get :

<pre>
<a href="css/">css/</a>
<a href="favicon.ico">favicon.ico</a>
<a href="imgs/">imgs/</a>
</pre>

Any clue to what I do incorrectly?

0 Answers
Related