Last active
March 30, 2017 04:58
-
-
Save KanybekMomukeyev/cd2f73e647e5e16a0484b75d298645e0 to your computer and use it in GitHub Desktop.
Channel queue example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//HTTP method | |
func (s *server) CreateOrderWith(ctx context.Context, creatOrdReq *pb.CreateOrderRequest) (*pb.CreateOrderRequest, error) { | |
ordReq := new(OrdReq) | |
ordReq.createOrdReq = creatOrdReq | |
ordReq.ctx = ctx | |
dbSaveChannel <- ordReq | |
select { | |
case createOrdReq := <-outputChannel: | |
return createOrdReq, nil | |
case error := <-errorChannel: | |
return nil, error | |
} | |
} | |
type OrdReq struct { | |
createOrdReq *pb.CreateOrderRequest | |
ctx context.Context | |
} | |
var dbSaveChannel chan *OrdReq | |
var outputChannel chan *pb.CreateOrderRequest | |
var errorChannel chan error | |
var db *sqlx.DB | |
func main() { | |
dbSaveChannel = make(chan *OrdReq) | |
outputChannel = make(chan *pb.CreateOrderRequest) | |
errorChannel = make(chan error) | |
go receiveDataFromInputChannel() | |
} | |
func receiveDataFromInputChannel() { | |
for ordReq := range dbSaveChannel { | |
creatOrdReq := ordReq.createOrdReq | |
ctx := ordReq.ctx | |
tx := db.MustBegin() | |
paymentSerial, err := model.StorePayment(tx, creatOrdReq.Payment) | |
if err != nil { | |
tx.Rollback() | |
log.WithFields(log.Fields{"err": err}).Warn("") | |
errorChannel <- err | |
} | |
creatOrdReq.Payment.PaymentId = paymentSerial | |
creatOrdReq.Order.PaymentId = paymentSerial | |
orderSerial, err := model.StoreOrder(tx, creatOrdReq.Order) | |
if err != nil { | |
tx.Rollback() | |
log.WithFields(log.Fields{"err": err}).Warn("") | |
errorChannel <- err | |
} | |
creatOrdReq.Order.OrderId = orderSerial | |
contexErr := ctx.Err() | |
if contexErr != nil { | |
tx.Rollback() | |
log.WithFields(log.Fields{"err": contexErr}).Warn("") | |
errorChannel <- err | |
} | |
err = tx.Commit() | |
if err != nil { | |
log.WithFields(log.Fields{"err": err}).Warn("") | |
errorChannel <- err | |
} | |
log.WithFields(log.Fields{"orderDocument": orderDocument}).Info("") | |
outputChannel <- creatOrdReq | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment