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

标签 http go goroutine

假设我有一个在服务器上运行的长时间运行的 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/

相关文章:

android - 将自定义 header 数据添加到 Android HTTP 请求

恰好 120 秒后 HTTP 504 超时

postgresql - 如何正确扫描 pq 数组?

multithreading - 如何安排运行的非阻塞函数

http - 如何启用nginx代理通行证?

php - 如何获取完整的 URL 以在 Laravel 中显示

Golang 将结构分配给另一个结构字段不起作用

performance - 如何测量golang中函数的执行时间,不包括等待时间

Goroutines、 channel 和死锁

java - Clojure/Java 中的 Goroutine 等价物