首页  >  文章  >  后端开发  >  在 Go 中显示访问令牌后如何手动关闭 HTTP 服务器?

在 Go 中显示访问令牌后如何手动关闭 HTTP 服务器?

Susan Sarandon
Susan Sarandon原创
2024-11-01 03:07:28334浏览

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