我有以下程序,其中使用 gorilla mux 创建 HTTP 服务器。当任何请求到来时,它启动 goroutine 1。在处理中,我正在启动另一个 goroutine 2。我想在 goroutine 1 中等待 goroutine 2 的响应?我怎么能这样做?如何确保只有 goroutine 2 会响应 goroutine 1?
GR3 可以创建 GR4,GR 3 应该只等待 GR4。
GR = Goroutine
服务器
package main
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"time"
"github.com/gorilla/mux"
)
type Post struct {
ID string `json:"id"`
Title string `json:"title"`
Body string `json:"body"`
}
var posts []Post
var i = 0
func getPosts(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
i++
fmt.Println(i)
ch := make(chan int)
go getTitle(ch, i)
p := Post{
ID: "123",
}
// Wait for getTitle result and update variable P with title
s := <-ch
//
p.Title = strconv.Itoa(s) + strconv.Itoa(i)
json.NewEncoder(w).Encode(p)
}
func main() {
router := mux.NewRouter()
posts = append(posts, Post{ID: "1", Title: "My first post", Body: "This is the content of my first post"})
router.HandleFunc("/posts", getPosts).Methods("GET")
http.ListenAndServe(":9999", router)
}
func getTitle(resultCh chan int, m int) {
time.Sleep(2 * time.Second)
resultCh <- m
}
德玛西亚99
繁星淼淼
相关分类