我一直在使用golang实现服务器。收到预期的参数“代码”后,我需要关闭服务器。在关闭服务器之前,我需要重定向到另一个网页。我已经实现如下。该代码有效。我需要知道这是否是最好的方法吗?感谢您的建议。
func main() {
var code string
const port int = 8888
httpPortString := ":" + strconv.Itoa(port)
mux := http.NewServeMux()
fmt.Printf("Http Server initialized on Port %s", httpPortString)
server := http.Server{Addr: httpPortString, Handler: mux}
var timer *time.Timer
mux.HandleFunc("/auth", func(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
fmt.Printf("Error parsing the code: %s", err)
}
code = r.Form.Get("code")
if err != nil {
log.Printf("Error occurred while establishing the server: %s", err)
}
http.Redirect(w, r, "https://cloud.google.com/sdk/auth_success", http.StatusMovedPermanently)
timer = time.NewTimer(2 * time.Second)
go func() {
<-timer.C
server.Shutdown(context.Background())
}()
})
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
fmt.Printf("Error while establishing the service: %s", err)
}
fmt.Println("Finished executing the the service")
}
谢谢 ..!
从此处引用的示例中获取@Peter冲洗的建议和想法:
f, ok := w.(http.Flusher)
if !ok {
http.Error(w, "no flush support", http.StatusInternalServerError)
return
}
http.Redirect(w, r, "https://cloud.google.com/sdk/auth_success", http.StatusSeeOther)
f.Flush() // <-- ensures client gets all writes
// this is done implicitly on http handler returns, but...
// we're shutting down the server now!
go func() {
server.Shutdown(context.Background())
close(idleConnsClosed)
}()
请参阅完整的Playground版本进行idleConnsClosed
设置/清理:https://play.golang.org/p/UBmLfyhKT0B
PS不要使用,http.StatusMovedPermanently
除非您真的希望用户不再使用源URL。用户的浏览器将缓存此(301)代码-不会访问您的服务器-可能不是您想要的。如果要临时重定向,请使用http.StatusSeeOther
(代码303)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句