Golang提供不同的回应

时间:2016-12-06 18:51:56

标签: json http go concurrency mux

我正在以example为基础在Go中编写REST API。

现在我遇到的问题是在对GET路由进行多个同时请求时,它会为所有待处理的客户端提供第一个结果。而不是仅将响应发送给请求客户端。

我一直在寻找几个小时,并尝试着我能想到的一切。 This是我发现的唯一一个看起来像我的问题的帖子,但没有解决我的问题。它导致json响应不完整..

从GET路由调用的句柄:

func Index(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)

    //some variable declaration here

    getResponses(w,...)
}

getResponses方法:

func getResponses(w http.ResponseWriter, ...) {
    responses := 0
    totalRequests = 0
    var completeChannel = make(chan string, 1)
    start = time.Now()

    go func() {
        totalRequests += 1
        //some method()

        responses += 1
        fmt.Println("method done")
        routineDone(responses, completeChannel)
    }()

    go func() {
        totalRequests += 1
        //some method()

        responses += 1
        fmt.Println("method done")
        routineDone(responses, completeChannel)
    }()



    select {
    case r := <-completeChannel:
        fmt.Println(r)
        sendResponse(w)
    case <-time.After(time.Second * 10):
        sendResponse(w)
    }
}

func routineDone(responses int, completeChannel chan string) {
    if totalRequests > 0 {
        fmt.Printf("completed %d of %s requests. duration: %s \n", responses, strconv.Itoa(totalRequests), time.Since(start))
    }

    if responses == totalRequests && totalRequests != 0 {
        completeChannel <- "DONE"
    }
}

func sendResponse(w http.ResponseWriter) {
    w.Header().Set("Content-Type", "application/json; charset=UTF-8")
    w.WriteHeader(http.StatusOK)
    if err := json.NewEncoder(w).Encode(globalJsonObject); err != nil {
        panic(err)
    }
}

0 个答案:

没有答案