Created
January 22, 2016 10:51
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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() | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just calling
ln.Close()on Line 23 won't work, becauseServeonhttp.Serverjust does what it says: Serving.Servewon't loop automatically, you have to do that yourself, which is surprisingly smart if you ask me.