dongliao3450 2016-01-26 14:38
浏览 70

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

Let's say I have a long-running programme in Go that is being ran on a server and, from time to time, the user needs to view its results (stats). We of course can create a screen session and make him login by SSH, reattach to the session etc, but it doesn't seem practical. As a better option, I want to launch some sort of embedded HTTP server which shall listen on some port like 8081 and, whenever requested, return the info in form of text (or JSON or XML or whatever). Basically it should just compose a string and return it through HTTP/1.1. It obviously should run in its own goroutin (in background). It is guarantied that the server receives low volume of traffic (e.g. no simultaneous requests) So probably there's something ready-to-use?

  • 写回答

1条回答 默认 最新

  • dstnlhhv791576 2016-01-26 20:44
    关注

    This will require some cooperative programming with your long-running program to listen for requests. It's also the perfect use case for a 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
    ", 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)
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。