首頁 >後端開發 >Golang >在 Go 中顯示訪問令牌後如何手動關閉 HTTP 伺服器?

在 Go 中顯示訪問令牌後如何手動關閉 HTTP 伺服器?

Susan Sarandon
Susan Sarandon原創
2024-11-01 03:07:28424瀏覽

How can I manually shut down an HTTP server after displaying the access token in Go?

顯示訪問令牌後手動關閉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&amp;redirect_uri=%v&amp;response_type=code&quot;, 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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn