Go:通过管道发送 gob 是挂起的 - 更新:进程外 http。响应编写器正在阻止



我正在编写一个网络服务器,该网络服务器将请求分发给GO中的未经进程程序。我正在使用GOB通过管道发送响应作者,并请求数据类型。

问题是在接收GOB时悬挂外部过程。

UPDATE 现在,GOB已成功发送到外部过程,但是现在外部过程在fmt.Fprintf(request.Resp, "Hello")处被阻止并在此处冻结。

dispreq.go

package dispreq
import (
    "net/http"
)
type DispReq struct {
    Resp    http.ResponseWriter
    Req *http.Request
}

dispatcher.go

package main
import (
    "encoding/gob"
    "fmt"
    "net/http"
    "os"
    "os/exec"
    "dispreq"
)
func dispatch(w http.ResponseWriter, r *http.Request) {
    process := exec.Command("./hello")
    pipe, piperr := process.StdinPipe()
    if piperr != nil {
        fmt.Fprintf(os.Stderr, piperr.Error())
        return
    }
    encoder := gob.NewEncoder(pipe)
    process.Stdout = os.Stdout
    //UPDATE: encoder.Encode(&dispreq.DispReq{w, r})
    //UPDATE: process.Start()
    process.Start()
    encoder.Encode(&dispreq.DispReq{w, r})
    pipe.Close()
    process.Wait()
}
func main() {
    http.HandleFunc("/", dispatch)
    http.ListenAndServe(":8080", nil)
}

你好。

package main
import (
    "dispreq"
    "encoding/gob"
    "os"
    "fmt"
)
func main() {
    gobDecoder := gob.NewDecoder(os.Stdin)
    var request dispreq.DispReq
    gobDecoder.Decode(&request)
    fmt.Fprintf(request.Resp, "Hello")
}

您应该在向其发送数据之前启动进程(process.Start())(encoder.Encode(&dispreq.DispReq{w, r}))。您可能还需要通过关闭管道(pipe.Close())或发送n来冲洗管道。

最新更新