Skip to content

Instantly share code, notes, and snippets.

@zacharysyoung
Created March 11, 2026 22:00
Show Gist options
  • Select an option

  • Save zacharysyoung/bedb346d76c1ad3ce9d82c6f78109b4b to your computer and use it in GitHub Desktop.

Select an option

Save zacharysyoung/bedb346d76c1ad3ce9d82c6f78109b4b to your computer and use it in GitHub Desktop.
Start a small ad-hoc server w/Go, and shutdown gracefully. Aimed at handling OAuth2 redirects to get auth code.
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
gotCode := make(chan struct{})
http.HandleFunc("/getcode", func(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
log.Printf("got auth-code=%s", q.Get("auth-code"))
close(gotCode)
})
srv := http.Server{Addr: ":8999"}
go func() {
sigint := make(chan os.Signal, 1)
signal.Notify(sigint, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
timeout := time.Tick(10 * time.Second)
select {
case <-gotCode:
log.Println("got code")
case <-timeout:
log.Println("timed out")
case <-sigint:
fmt.Print("\r")
log.Println("interrupted")
}
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
log.Println("shutting down")
if err := srv.Shutdown(ctx); err != nil {
log.Fatalf("trouble shutting down listeners: %v", err)
}
}()
log.Println("starting")
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
log.Fatalf("problem with server: %v", err)
}
log.Println("done")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment