PPysolate SpineREAD THE CODE · UNDERSTAND THE SYSTEM
课程与章节
源码索引 / CURRENT IMPLEMENTATION

learning/go-patterns/stages/05-parallel/quote.go

51 行 · 点击行号可定位;函数链接随声明位置更新,不手填行号。

跳到函数 / 声明
package main

import (
	"context"
	"errors"
	"fmt"
)

var ErrUnknownItem = errors.New("unknown item")

type Price struct {
	Item  string
	Cents int
}
type PriceSource interface {
	Lookup(context.Context, string) (Price, error)
}
type Catalog map[string]int

func (c Catalog) Lookup(ctx context.Context, item string) (Price, error) {
	if err := ctx.Err(); err != nil {
		return Price{}, err
	}
	cents, ok := c[item]
	if !ok {
		return Price{}, fmt.Errorf("%w: %q", ErrUnknownItem, item)
	}
	return Price{Item: item, Cents: cents}, nil
}

type Service struct{ source PriceSource }

func NewService(source PriceSource) Service { return Service{source: source} }
func (s Service) Quote(ctx context.Context, item string) (Price, error) {
	var price, shipping Price
	_, err := RunTwo(ctx,
		func(ctx context.Context) (string, error) {
			var err error
			price, err = s.source.Lookup(ctx, item)
			return "", err
		},
		func(ctx context.Context) (string, error) {
			var err error
			shipping, err = s.source.Lookup(ctx, "shipping")
			return "", err
		})
	if err != nil {
		return Price{}, err
	}
	return Price{Item: item, Cents: price.Cents + shipping.Cents}, nil
}