Stopping a web server using a web request

This is an example Go program which demonstrates stopping a web server using a user request. The server prints a message to the web page before it shuts itself down.

package main

import (
        "context"
        "fmt"
        "log"
        "net/http"
)

var cancel context.CancelFunc
var ctx context.Context
var server *http.Server

func servePage(w http.ResponseWriter, r *http.Request) {
        command := r.FormValue("command")
        if command == "stop" {
                fmt.Fprintf(w, "I am stopping.\n")
                log.Printf("Stopping at user request.\n")
                cancel()
                return
        }
        log.Printf("Serving a page %s.\n", r.RequestURI)
        fmt.Fprintf(w, `<html>
<p>
I am a web server.</p>
<form>
<button name="command" value="stop">Stop the web server</button>
</form>
</html>
`)
}

func main() {
        http.HandleFunc("/", servePage)
        ctx, cancel = context.WithCancel(context.Background())
        server = &http.Server{Addr: ":8080"}
        go func() {
                err := server.ListenAndServe()
                switch err {
                case http.ErrServerClosed:
                        log.Printf("The server has shut itself down.\n")
                default:
                        log.Printf("Error from server: %s\n", err)
                }
        }()
        <-ctx.Done()
        err := server.Shutdown(context.Background())
        if err != nil {
                log.Printf("Error shutting down server: %s\n", err)
        }
}

(download)

The output of the example, given first a request to run, and then after pressing the stop button, looks like this:

2023/03/13 14:18:39 Serving a page /.
2023/03/13 14:18:39 Serving a page /favicon.ico.
2023/03/13 14:18:40 Stopping at user request.
2023/03/13 14:18:40 The server has shut itself down.


Copyright © Ben Bullock 2009-2024. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer