http.ListenAndServe:程序退出时关闭

I want to write simple REST API application. I wrote the code handling HTTP-requests:

package main

import (
    "fmt"
    "log"
    "movies/dao"
    "net/http"

    "github.com/gorilla/mux"
)

var d = dao.MoviesDAO{}

// AllMoviesEndPoint show all movies
func AllMoviesEndPoint(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "not implemented yet")
}

func init() {
    d.Server = "127.0.0.1"
    d.Database = "movies"
}

func main() {
    //d.Connect()
    router := mux.NewRouter()
    router.HandleFunc("/movies", AllMoviesEndPoint).Methods("GET")

    go func() {
        if err := http.ListenAndServe(":3000", router); err != nil {
            log.Fatal(err)
        }
    }()
}

But when I run this prgram under debugger and then stop it, socket is bind'ed, I can access server from browser, and I can not run program another time since I get a error listen tcp :3000: bind: address already in use.

How to close connection when program exits?

Now I need to kill -9 PID my server to start new debug session.

The problem is not in the debugger, the problem is in your code.

When you write

go func() {
    if err := http.ListenAndServe(":3000", router); err != nil {
        log.Fatal(err)
    }
}()

you're creating a new goroutine that's completely independent by the main thread.

This means that the execution of your main is:

  1. Create router
  2. Create and execute a goroutine
  3. end of main, return and kill all childs

There's nothing making the main waiting for the go routine execution and termination.

Since http.ListenAndServe creates a thread that waits indefinitely for new connections, you don't need to create it inside a goroutine.

Hence, just remove the go func() { block and you'll be ok.