gpt4 book ai didi

在单独的 goroutine 中显示进度的 HTTP 服务器

转载 作者:数据小太阳 更新时间:2023-10-29 03:42:33 24 4
gpt4 key购买 nike

假设我有一个在服务器上运行的长时间运行的 Go 程序,用户有时需要查看其结果(统计信息)。我们当然可以创建一个屏幕 session 并让他通过 SSH 登录,重新附加到 session 等,但这似乎不太实用。作为一个更好的选择,我想启动某种嵌入式 HTTP 服务器,该服务器应在 8081 等端口上监听,并在请求时以文本(或 JSON 或 XML 或其他)形式返回信息。基本上它应该只是组成一个字符串并通过 HTTP/1.1 返回它。它显然应该在自己的 goroutin 中运行(在后台)。保证服务器收到低流量(例如,没有同时请求)那么可能有一些现成的东西?

最佳答案

这将需要与您的长期运行程序进行一些协作编程来监听请求。它也是 chan chan

的完美用例
// inside your main package

// MakeResponse listens for a request for information and serves it back on
// request's channel.
func MakeResponse(request chan chan interface{}) {
// I'm not sure what kind of raw data you're trying to throw back, but
// you probably don't want to do your encoding to json here. Do that in
// your webserver instead.

for resp := range request {
resp <- getInternalStateInformation()
}
}

// inside your listener package

var requests chan chan interface{}

func init() {
requests = make(chan chan interface{}, 10)
}

func RequestInfo(w http.ResponseWriter, r *http.Request) {
response := make(chan interface{})
requests<-response
data := <-response
outData, err := json.Marshal(data)
if err != nil {
log.Printf("Couldn't marshal data %v\n", data)
}
fmt.Fprint(w, outData) // or more likely execute a template with this
// context
}

func main() {
defer close(requests)
go longrunningprog.MakeResponse(requests)
http.HandleFunc("/", RequestInfo)
http.ListenAndServe(":8081", nil)
}

关于在单独的 goroutine 中显示进度的 HTTP 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35016420/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com