在休息时使用 goroutine api - 出现未定义的错误

Working with goroutine in a rest api - getting undefined error

正在学习围棋,想简单休息一下API。

我想做的是在处理完 api 请求后触发一个 goroutine,并在后台异步完成工作。

到目前为止,这是我的实现:

package main

import (
    "encoding/json"
    "log"
    "net/http"

    "github.com/julienschmidt/httprouter"
)

// APIResponse represents common structure of every api call response
type APIResponse struct {
    Status string `json:"status"`
    Error  string `json:"error,omitempty"`
    Data   string `json:"data,omitempty"`
}

// Action represents what could be passed to the goroutine
type Action = func()

// ActionQueue represents a buffered channel
type ActionQueue = chan Action

func main() {
    r := httprouter.New()
    r.GET("/test", test)

    var apiServerPort = ":80"
    err := http.ListenAndServe(apiServerPort, r)
    if err != nil {
        log.Fatal("ListenAndServe:", err)
    } else {
        log.Printf("Started server on port %s", apiServerPort)
    }

    var queueSize = 10
    queue := make(ActionQueue, queueSize)
    for i := 0; i < queueSize; i++ {
        go worker(queue)
    }
    log.Printf("Started %d queue workers", queueSize)
}

func test(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
    successResponse(w, http.StatusOK, "Hello World")
    queue <- func() {
        log.Println("Hello from queue worker, initiated by api call")
    }
}

func successResponse(w http.ResponseWriter, statusCode int, successData string) {
    sendResponse(w, statusCode, "", successData)
}

func errorResponse(w http.ResponseWriter, statusCode int, errorData string) {
    sendResponse(w, statusCode, errorData, "")
}

func sendResponse(w http.ResponseWriter, statusCode int, errorData string, responseData string) {
    w.WriteHeader(statusCode)
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(&APIResponse{Status: http.StatusText(statusCode), Error: errorData, Data: responseData})
}

func worker(queue ActionQueue) {
    for action := range queue {
        action()
    }
}

当我尝试 运行 这段代码时,出现以下错误(在这一行 queue <- func() { ... }):

./main.go:46:2: undefined: queue

如何使 queue 通道可用于我的请求处理程序(即 httprouter GET 请求处理程序函数)?

其次,我无法在控制台输出 (stdout) 中看到 log.Printf() 调用的输出,例如应用程序 运行 时的服务器状态消息。有什么想法吗?

有几处不对劲,首先你的 main 函数没有正确排序,你想在你之前初始化你的通道并启动 worker 运行 err := http.ListenAndServe(apiServerPort, r) 所以像这样

func main() {
    var queueSize = 10
    queue := make(ActionQueue, queueSize)
    for i := 0; i < queueSize; i++ {
        go worker(queue)
    }
    log.Printf("Started %d queue workers", queueSize)

    // routers and stuff...
}

然后 queue 变量未在 test() 函数中定义,这就是您得到 ./main.go:46:2: undefined: queue 的原因。您可以使用高阶函数修复它,例如

func test(queue ActionQueue) httprouter.Handle {
    return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
        successResponse(w, http.StatusOK, "Hello World")
        queue <- func() {
            log.Println("Hello from queue worker, initiated by api call")
        }
    }
}

然后用r.GET("/test", test(queue))

将它绑定到路由