英文:
Shutdown web server after the request is handled - Go
问题
我有一个函数,当运行时会给用户一个URL,用于开始与我的客户端进行令牌交换的OAuth流程。
我需要运行一个本地HTTP服务器来接受用户的回调。但是我不确定在流程完成后如何关闭HTTP服务器、关闭函数并继续执行。
func OAuth(request *OAuthRequest) {
http.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{"response": "无法处理请求"}`))
// 做一些操作
// 完成并关闭HTTP服务器
})
err := http.ListenAndServe(net.JoinHostPort("", "8080"), nil)
if err != nil {
log.Fatalln(err)
}
fmt.Println("登录地址:www.example.com/123abc")
// 等待用户完成流程
}
- 用户调用
.OAuth()
- 启动本地服务器并公开
/callback
- 用户获得在浏览器中使用的URL
- 远程服务器将回调发送到localhost/callback
- 本地HTTP服务器处理响应
- 工作完成,关闭本地HTTP服务器
.OAuth()
完成
英文:
I have a function that when run will give a user a URL to use to start an OAuth flow for a token exchange with my client.
I need to run a local HTTP server to accept the callback for the user. But I'm not sure how to then shutdown the HTTP server and close the function and move on once the flow is done.
func OAuth(request *OAuthRequest) {
http.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{"response": "unable to handle request"}`))
// Do something
// Finish up and shutdown HTTP server
})
err := http.ListenAndServe(net.JoinHostPort("","8080"), nil)
if err != nil {
log.Fatalln(err)
}
fmt.Println("Login at: www.example.com/123abc")
// Wait for user to finish flow
}
- User calls
.OAuth()
- Local server is started and exposes
/callback
- User is given URL to use in browser
- Remote server sends callback to localhost/callback
- Local HTTP server handles response
- Job done, shutdown local HTTP server
.OAuth()
is complete
答案1
得分: 3
你需要通过http.Server
来创建HTTP服务器,如果你想要能够关闭它:
package main
import (
"context"
"fmt"
"net/http"
)
func main() {
mux := http.NewServeMux()
srv := http.Server{
Addr: "localhost:8080",
Handler: mux,
}
mux.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{"response": "无法处理请求"}`))
go srv.Shutdown(context.Background())
})
fmt.Println("登录网址:www.example.com/123abc")
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
panic(err)
}
}
英文:
You need to create the HTTP server via http.Server
if you want to be able to shut it down:
package main
import (
"context"
"fmt"
"net/http"
)
func main() {
mux := http.NewServeMux()
srv := http.Server{
Addr: "localhost:8080",
Handler: mux,
}
mux.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{"response": "unable to handle request"}`))
go srv.Shutdown(context.Background())
})
fmt.Println("Login at: www.example.com/123abc")
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
panic(err)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论