我对 golang 比较陌生,我想创建一种方法来同时调用多个 URL,并解析 JSON 文档。但是,我真的不确定我是否正确使用了 goroutine 和 channels。在这一点上,我不确定我是否没有正确地“在 Go 中思考”,或者我对 goroutine 和通道的理解/方法是否不准确。
此外,在解析时,我想results
从 body 中解析属性,这是一个数组,其中的每个元素都results
包含一个doc
我想过滤掉的属性。
目标是同时进行多次提取,并仅解析doc
响应正文结果数组中的属性的响应。
绝对会感谢任何见解或建议以更好地理解事物。提前致谢。
package operations
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"strings"
)
// CouchbaseDoc parses .doc property from sync gateway documents
type CouchbaseDoc struct {
Doc map[string]string `json:"doc"`
}
// Results deconstruct... results is a property of body, and is an array of obects
type Results struct {
Results []byte `json:"results"`
}
func createURLs(channels []string) map[string]string {
urlMap := make(map[string]string)
domain := "swap" + strings.TrimSpace(os.Getenv("env"))
bucket := strings.TrimSpace(os.Getenv("bucket"))
for _, doctype := range channels {
urlMap[doctype] = fmt.Sprintf("https://%s.endpoint.com/%s/_changes?filter=sync_gateway/bychannel&channels=%s&include_docs=true", domain, bucket, doctype)
}
return urlMap
}
func getChangesFeed(url string, ch chan map[string]string) {
resp, _ := http.Get(url)
body, _ := ioutil.ReadAll(resp.Body)
go parseBody(body, ch)
}
func parseBody(body []byte, ch chan map[string]string) {
var results Results
var doc CouchbaseDoc
json.Unmarshal(body, &results)
json.Unmarshal(results.Results, &doc)
// write to responses
ch <- doc.Doc
}
func fetchDocs(channels []string) {
urls := createURLs(channels)
// Response channel is where all go routines will do the dirty
responses := make(chan map[string]string)
for _, url := range urls {
go getChangesFeed(url, responses)
}
// Read from responses channel
docs := <-responses
for doc := range docs {
fmt.Println(doc) // This should print results ??
}
}