【发布时间】:2021-09-12 12:40:50
【问题描述】:
我想返回并终止 checkSomeThing 函数中的请求。但问题是进程继续,除非到达main() 的末尾,否则不会返回响应。这是我的代码:
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", handler)
// ...
http.ListenAndServe(":8080", nil)
}
func handler(w http.ResponseWriter, r *http.Request) {
checkSomeThing(w, r)
http.Error(w, "Operation completed!", http.StatusOK)
fmt.Println("End of Handler.")
}
func checkSomeThing(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Bad Request!", http.StatusBadRequest)
return
}
运行程序后输出如下:
// Output:
< HTTP/1.1 400 Bad Request
< Content-Type: text/plain; charset=utf-8
< X-Content-Type-Options: nosniff
< Date: Sun, 12 Sep 2021 12:38:49 GMT
< Content-Length: 34
<
Bad Request!
Operation completed!
【问题讨论】:
-
test函数在哪里?你的意思是checkSomeThing?