顯示訪問令牌後手動關閉HTTP 伺服器
要解決關閉HTTP 伺服器時遇到的錯誤,您可以使用上下文.WithCancel函數。這種方法涉及創建一個可以手動取消的上下文,從而允許您優雅地關閉伺服器。
<code class="go">package main import ( "context" "fmt" "io" "log" "net/http" "time" ) var client_id = "my_client_id" var client_secret = "my_client_secret" var redirect_url = "http://localhost:8000/instagram/callback" func main() { ctx, cancel := context.WithCancel(context.Background()) srv := startHttpServer(ctx) openbrowser(fmt.Sprintf("https://api.instagram.com/oauth/authorize/?client_id=%v&redirect_uri=%v&response_type=code", client_id, redirect_url)) // Listen for context cancellation signals go func() { <-ctx.Done() // Gracefully shut down the server if err := srv.Shutdown(context.Background()); err != nil { panic(err) // failure/timeout shutting down the server gracefully } }() time.Sleep(20 * time.Second) cancel() } func showTokenToUser(w http.ResponseWriter, r *http.Request) { io.WriteString(w, fmt.Sprintf("Your access token is: %v", r.URL.Query().Get("code"))) } func startHttpServer(ctx context.Context) *http.Server { srv := &http.Server{Addr: ":8000"} http.HandleFunc("/instagram/callback", showTokenToUser) http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "Hello world!") }) go func() { if err := srv.ListenAndServe(); err != http.ErrServerClosed { // cannot panic, because this probably is an intentional close log.Fatalf("Httpserver: ListenAndServe() error: %s", err) } }() // Return the server reference for use in shutting down return srv } func openbrowser(url string) { var err error switch runtime.GOOS { case "linux": err = exec.Command("xdg-open", url).Start() case "windows": err = exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start() case "darwin": err = exec.Command("open", url).Start() default: err = fmt.Errorf("unsupported platform") } if err != nil { log.Fatal(err) } }</code>
此解決方案利用單獨的 goroutine 來處理上下文取消和優雅的伺服器關閉。當使用者存取 /quit 路由時,上下文被取消,從而觸發伺服器關閉過程。
以上是在 Go 中顯示訪問令牌後如何手動關閉 HTTP 伺服器?的詳細內容。更多資訊請關注PHP中文網其他相關文章!