How do I stop a Listening server in Go

前端 未结 4 1993
长发绾君心
长发绾君心 2020-12-29 06:09

I\'ve been trying to find a way to stop a listening server in Go gracefully. Because listen.Accept blocks it is necessary to close the listening socket to sign

4条回答
  •  爱一瞬间的悲伤
    2020-12-29 06:39

    Here's a simple way that's good enough for local development.

    http://www.sergiotapia.me/how-to-stop-your-go-http-server/


    package main
    
    import (  
        "net/http"
        "os"
    
        "github.com/bmizerany/pat"
    )
    
    var mux = pat.New()
    
    func main() {  
        mux.Get("/kill", http.HandlerFunc(kill))
        http.Handle("/", mux)
        http.ListenAndServe(":8080", nil)
    }
    
    func kill(w http.ResponseWriter, r *http.Request) {  
        os.Exit(0)
    }
    

提交回复
热议问题