5

My code is just the same as in gowiki

package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

However, after I build and run this program, it exit immediately without blocking so that I get no response when I try to access http://localhost:8080/monkey from Chrome.

Environment: Ubuntu 14(in VirtualBox on Windows7)

Why?

1
  • Do you have anything else using port 8080? Are there any error messages? Commented Aug 4, 2014 at 15:11

3 Answers 3

20

Check the error returned from ListenAndServe

func main() {
    http.HandleFunc("/", handler)
    fmt.Println(http.ListenAndServe(":8080", nil))
}
Sign up to request clarification or add additional context in comments.

Comments

5

http.ListenAndServe function returns an object that conforms error interface. If the call does not block, it definitely means that some kind of error has happened. The most popular are:

  • there is already another process listening that port
  • your user has no right to bind socket on port 8080, or 0.0.0.0 interface

Comments

1

In my case, it was a permission denied error. Using sudo worked like a charm.

sudo go run filename.go

or

sudo filename

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.