1. 程式人生 > >Go channel 使用示例程式碼

Go channel 使用示例程式碼

package main

import (
	"fmt"
)

type Person struct {
	ID   string `json: "id"`
	Name string `json: "name"`
}

type PersonHandler interface {
	bath(origs <-chan Person) <-chan Person
	handle(orig Person)
	fetchPerson(origs chan<- Person)
	savePerson(dest <-chan Person) <-chan bool
}

type PersonHanlerImpl struct{}

func getPersonHandler() PersonHandler {
	return PersonHanlerImpl{}
}

func (handler PersonHanlerImpl) bath(origs <-chan Person) <-chan Person {
	dests := make(chan Person, 100)
	go func() {
		for {
			orig, ok := <-origs
			if !ok {
				close(dests)
				break
			}
			handler.handle(orig)
			dests <- orig
		}
	}()
	return dests
}

func (handler PersonHanlerImpl) handle(orig Person) {
	fmt.Printf("name: %s\n", orig.Name)
}

func (handler PersonHanlerImpl) fetchPerson(origs chan<- Person) {
	p := Person{ID: "003", Name: "user03"}
	origs <- p
}

func (handler PersonHanlerImpl) savePerson(orig <-chan Person) <-chan bool {
	rc := make(chan bool)
	go func() {
		o, ok := <-orig
		if !ok {
			fmt.Println("channel has been closed")
		}
		handler.handle(o)
		rc <- true
	}()
	return rc
}

func main() {
	// test batch
	personHandlerImple := PersonHanlerImpl{}
	batchChan := make(chan Person, 2)
	batchChan <- Person{ID: "001", Name: "user01"}
	batchChan <- Person{ID: "002", Name: "user02"}
	batchResult := personHandlerImple.bath(batchChan)
	<-batchResult

	// test fetch
	fetchChan := make(chan Person, 1)
	personHandlerImple.fetchPerson(fetchChan)
	fetchResult := <-fetchChan
	fmt.Printf("got person with id=%s, name=%s\n", fetchResult.ID, fetchResult.Name)

	// test save
	saveChan := make(chan Person, 1)
	saveChan <- Person{ID: "004", Name: "user04"}
	saveResult := personHandlerImple.savePerson(saveChan)
	saveValue := <-saveResult
	fmt.Printf("save result: %v\n", saveValue)
}