-2

I'm learning go language and I still have some lack of knowledge. I'm writing http static server (in 1st phase to serve assets). Also I'm trying to use gorilla/mux package as router.

So far I ended up with

pagekage main

import (
    "fmt"
    "github.com/gorilla/mux"
    "html"
    "net/http"
)

func HomeHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
}

func main() {

    r := mux.NewRouter()
    r.HandleFunc("/", HomeHandler)
    r.PathPrefix("/public/").Handler(http.StripPrefix("/public/",
        http.FileServer(http.Dir("public/"))))

    http.Handle("/", r)
    http.ListenAndServe(":8080", nil)

}

it works fine and serves all files under /public/

Now I'd like to refactor code

r.PathPrefix("/public/").Handler(http.StripPrefix("/public/",
            http.FileServer(http.Dir("public/"))))

to be in form

r.PathPrefix("/public/").Handler(PublicHandler)

It's quite basic and I'd like to learn how to make better looking code.

Can you advice on this? Thx.

Jaro
  • 3,799
  • 5
  • 31
  • 47

1 Answers1

1

Simply assign the handler to a variable:

PublicHandler := http.StripPrefix("/public/", http.FileServer(http.Dir("public/")))
r.PathPrefix("/public/").Handler(PublicHandler)
JimB
  • 104,193
  • 13
  • 262
  • 255
  • Hi JimB, yes I know that I can do is as you wrote above. I'm thinking to move PublicHandler := http.StripPrefix("/public/", http.FileServer(http.Dir("public/"))) to its own function. And this step causing me difficulties. – Jaro May 09 '14 at 08:06
  • @Jaro: Please post an example of what you're really asking. There's no reason you can't return PublicHandler from a function. – JimB May 09 '14 at 14:15