我的目標是 curl 客戶端向 Go API 發(fā)送 http req,而 Go API 確實如此(1. 運行后臺 shell,2. 立即向客戶端返回響應(yīng),但 3. 繼續(xù)在后臺運行第 1 點服務(wù)器端命令)。問題是第 2 點沒有立即返回給客戶端,客戶端僅在第 3 點完成后才得到響應(yīng)我試過:import ( "fmt" "io" "io/ioutil" "net/http" "os" "os/exec" "log" "strings" "flag" "strconv" "crypto/tls" "crypto/x509" "github.com/gorilla/handlers" "github.com/gorilla/mux" "github.com/go-ldap/ldap" "regexp" "errors" "encoding/base64" "time")func insert(w http.ResponseWriter, r *http.Request) (error) {fullcmd := fmt.Sprintf("/home/ec2-user/spark_home/bin/spark-submit %s", "dgs")cmd := exec.Command("/bin/sh", "-c", fullcmd)err4 := cmd.Start()if err4 != nil { e1 := fmt.Sprintf("Error") l.Printf(e1) http.Error(w, e1, http.StatusInternalServerError) return err4} else { l.Printf("The data is being ingested asynchronously in the background \n") fmt.Fprintf(w, "request received. The data is being ingested asynchronously in the background \n") w.Header().Set("Content-Type", "text/plain") w.Write([]byte(fmt.Sprintf("request received. The data is being ingested asynchronously in the background \n")))}//wait for the spark command to finish, need to Wait() otherwise zombie/orphan pid is createdcmd.Wait()//do bunch of other commands here that take 30+ secondsl.Printf("success") return nil}r := mux.NewRouter() r.HandleFunc("/test", insert).Methods(http.MethodPost) http.Handle("/", r) server := &http.Server{ Addr: ":" + strconv.Itoa(*port), Handler: handlers.LoggingHandler(os.Stdout, http.DefaultServeMux), TLSConfig: tlsConfig, } server.ListenAndServeTLS(TLS_SERVER_CERTFILE, TLS_SERVER_KEYFILE)
1 回答

UYOU
TA貢獻1878條經(jīng)驗 獲得超4個贊
當 HTTP 處理程序返回時,響應(yīng)將完成,因此如果您想啟動一個將繼續(xù)的作業(yè),您必須在單獨的 goroutine 中執(zhí)行此操作。您可以在 shell 進程啟動后立即啟動 goroutine,使用如下所示:
func insert(w http.ResponseWriter, r *http.Request) (error) {
...
err4 := cmd.Start()
if err4 != nil {
...
}
w.Header().Set("Content-Type", "text/plain")
fmt.Fprintf(w, "request received. The data is being ingested asynchronously in the background \n")
go func() {
cmd.Wait()
// Do other stuff
}()
return nil
}
- 1 回答
- 0 關(guān)注
- 125 瀏覽
添加回答
舉報
0/150
提交
取消