2

I try to handle HTTP request using mux instead of standart HandleFunc from net/http, because of reasons. With http it used to work, with mux it doesnt.

import (
    _ "github.com/go-sql-driver/mysql"
    "github.com/gorilla/mux"
    _ "io/ioutil"
    "net/http"
)


func init() {

    mx := mux.NewRouter()

    //create a poll
    mx.HandleFunc("/poll", pollCreate)
    mx.HandleFunc("/poll/{id}", loadPoll)
    mx.HandleFunc("/poll/vote", castVote)

    http.ListenAndServe(":8080", mx)
}

The following POST request

localhost:8080/poll

Results in:

INFO     2015-06-02 16:23:12,219 module.py:718] default: "POST /poll HTTP/1.1" 404 19
2
  • 1
    I can't reproduce this with a simple program (play.golang.org/p/9QQEkVED8i). Do you have a minimal, complete, verifiable test case that demonstrates the problem? Commented Jun 2, 2015 at 16:47
  • 1
    module.py suggests that you already have a python program listening to that port and your Go app failed to bind to the port Commented Jun 2, 2015 at 17:41

2 Answers 2

3

Found solution.

Change

http.ListenAndServe(":8080", mx)

To

http.Handle("/", mx)
Sign up to request clarification or add additional context in comments.

1 Comment

This needs more of an explanation. You no longer specify the port to listen on, so... what's going on here?
0

You forgot to add the default handler. It's always better to keep the method along with the handlers.

 import (
        _ "github.com/go-sql-driver/mysql"
        "github.com/gorilla/mux"
        _ "io/ioutil"
        "net/http"
    )


func init() {

    mx := mux.NewRouter()

    //create a poll
    mx.Path("/").HandlerFunc(indexHandler)
    mx.PathPrefix("/poll", pollCreate).Method("POST)
    mx.PathPrefix("/poll/{id}", loadPoll)
    mx.PathPrefix("/poll/vote", castVote)

    http.ListenAndServe(":8080", mx)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.