这段代码从标准输入中获取文本,将其映射到结构(如果可能的话),并由此创建一个JSON字符串。
我使用条形码扫描器作为输入,我尝试使用goroutines来确保如果解析或JSON编组出现问题,程序将继续接收和处理来自扫描仪的输入。
我做得对吗?我是以最有效、最有效率、最惯用的方式做的吗?
因为我只关心这个帖子的并发性,所以我忽略了所有解析输入和创建JSON的代码。另外,我现在对JSON所做的唯一事情就是把它打印出来。
谢谢你看这个。
package main
import (
"fmt"
"status2/shoporder"
)
func main() {
var input string
for input != "exit" {
fmt.Scanln(&input)
ch := make(chan string)
quit := make(chan bool)
go parseInput(input, ch, quit)
go sendJson(ch, quit)
}
}
// Take the input and generate some JSON, then return it along a channel.
func parseInput(input string, ch chan string, quit chan bool) {
// shoporder.Parse() uses regexp to validate the input, and returns a JSON string.
son, ok := shoporder.Parse(input)
if !ok {
// If the input could not be parsed into JSON, then ignore and shut down
// both goroutines.
quit <- true
return
}
ch <- son
}
// This will eventually send the JSON using websockets, but for now I just
// print it back out.
func sendJson(ch chan string, quit chan bool) {
select {
case json := <-ch:
// For now I just print the JSON.
fmt.Println(json)
case <-quit:
// I make sure to quit the goroutine, because I'm worried about creating a
// bunch that never end and just hang around. Do I need to do this?
return
}
}发布于 2013-02-25 18:55:59
为每个输入启动一个goroutine似乎是合理的,但我不确定您是否需要单独的goroutine来解析和发送。毕竟,其中一个只是在等待另一个完成。他们也可能是同一条猩猩。然后你不需要任何一个频道,因为他们只是让这两个猩猩沟通。
https://codereview.stackexchange.com/questions/23050
复制相似问题