Search code examples
gomux

gorilla mux router handlers


I can not get the gorilla mux to work..

When requesting http://www.localhost:9000 this is returned by the web server 404 page not found

But this works http://localhost:9000/ and prints Hello world

package main

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

func Handler(w http.ResponseWriter, r *http.Request){
    fmt.Fprint(w, "Hello world")
}

func main(){
    r := mux.NewRouter()
    r.Host("www.localhost")
    r.HandleFunc("/", Handler)
    err := http.ListenAndServe(":9000", r)
    if err != nil {
        log.Fatal("ListenAndServe error: ", err)
    }
}

Solution

  • You want to be able to support both localhost and www.localhost

    package main
    
    import (
            "fmt"
            "log"
            "net/http"
    
            "github.com/gorilla/mux"
    )
    
    func Handler(w http.ResponseWriter, r *http.Request) {
            fmt.Fprint(w, "Hello world")
    }
    
    func main() {
            r := mux.NewRouter()
            r.Host("www.localhost").Path("/").HandlerFunc(Handler)
            r.HandleFunc("/", Handler)
            err := http.ListenAndServe(":9000", r)
            if err != nil {
                    log.Fatal("ListenAndServe error: ", err)
            }
    }
    

    If you read the documentation carefully, you'll notice that r.Host() is just another pattern matching function. It doesn't set any global rule for that router.

    if you want to make that rule to be inherited you'll need to use a subrouter:

    subrouter := r.Host("www.localhost").Subrouter()
    

    then you use "subrouter" in place of "r"