github.com/searKing/golang/go@v1.2.117/x/dispatch/example_test.go (about)

     1  // Copyright 2020 The searKing Author. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package dispatch_test
     6  
     7  import (
     8  	"context"
     9  	"errors"
    10  	"log"
    11  
    12  	"github.com/searKing/golang/go/x/dispatch"
    13  )
    14  
    15  type DispatchMsg struct {
    16  	data int
    17  }
    18  
    19  func ExampleDispatch() {
    20  	var conn chan DispatchMsg
    21  	dispatch.NewDispatch(
    22  		dispatch.ReaderFunc(func(ctx context.Context) (any, error) {
    23  			return ReadMessage(conn)
    24  		}),
    25  		dispatch.HandlerFunc(func(ctx context.Context, msg any) error {
    26  			m := msg.(*DispatchMsg)
    27  			return HandleMessage(m)
    28  		})).Start()
    29  }
    30  
    31  func ExampleDispatcher_Join() {
    32  	var conn chan DispatchMsg
    33  
    34  	workflow := dispatch.NewDispatch(
    35  		dispatch.ReaderFunc(func(ctx context.Context) (any, error) {
    36  			return ReadMessage(conn)
    37  		}),
    38  		dispatch.HandlerFunc(func(ctx context.Context, msg any) error {
    39  			m := msg.(*DispatchMsg)
    40  			return HandleMessage(m)
    41  		})).Joinable()
    42  
    43  	go func() {
    44  		workflow.Start()
    45  	}()
    46  	const cnt = 10
    47  	for i := 0; i < cnt; i++ {
    48  		conn <- DispatchMsg{data: i}
    49  	}
    50  	workflow.Join()
    51  }
    52  func ExampleDispatcher_Context() {
    53  	var conn chan DispatchMsg
    54  
    55  	workflow := dispatch.NewDispatch(
    56  		dispatch.ReaderFunc(func(ctx context.Context) (any, error) {
    57  			return ReadMessage(conn)
    58  		}),
    59  		dispatch.HandlerFunc(func(ctx context.Context, msg any) error {
    60  			m := msg.(*DispatchMsg)
    61  			return HandleMessage(m)
    62  		})).Joinable()
    63  	go func() {
    64  		workflow.Start()
    65  	}()
    66  	workflow.Context().Done()
    67  	workflow.Join()
    68  }
    69  
    70  func ReadMessage(c <-chan DispatchMsg) (any, error) {
    71  	var msg DispatchMsg
    72  	var ok bool
    73  
    74  	if msg, ok = <-c; ok {
    75  		log.Println("Recv From Channel Failed")
    76  		return nil, errors.New("recv from channel failed")
    77  	}
    78  	log.Printf("Recv From Channel Success: %v\n", msg.data)
    79  	return &msg, nil
    80  }
    81  
    82  // just print what's received
    83  func HandleMessage(msg *DispatchMsg) error {
    84  	if msg == nil {
    85  		log.Println("Handle From Channel Failed")
    86  		return errors.New("handle from channel failed")
    87  	}
    88  	log.Printf("Handle From Channel Success: %v\n", msg.data)
    89  	return nil
    90  }