Skip to content

Instantly share code, notes, and snippets.

@gr4y
Created January 22, 2016 10:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gr4y/cadc8db0cc75c30aa784 to your computer and use it in GitHub Desktop.
Save gr4y/cadc8db0cc75c30aa784 to your computer and use it in GitHub Desktop.
Stopping an http.Server via channel. I want to use this for OAuth2 in an command line application, I don't want to be an web application.
package main
import (
"fmt"
"net"
"net/http"
// "os"
)
func main() {
ln, err := net.Listen("tcp", ":1413")
if err != nil {
panic(err)
}
stop := make(chan bool)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("It works!"))
})
http.HandleFunc("/shutdown", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("This will stop the server! \n"))
stop <- true
})
server := http.Server{}
go func() {
server.Serve(ln)
}()
fmt.Printf("Servy-serv %s\n", ln.Addr().String())
select {
case <-stop:
ln.Close()
}
}
@gr4y
Copy link
Author

gr4y commented Jan 22, 2016

Just calling ln.Close() on Line 23 won't work, because Serve on http.Server just does what it says: Serving. Serve won't loop automatically, you have to do that yourself, which is surprisingly smart if you ask me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment