github.com/ethw3/go-ethereuma@v0.0.0-20221013053120-c14602a4c23c/node/node_example_test.go (about)

     1  // Copyright 2015 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package node_test
    18  
    19  import (
    20  	"fmt"
    21  	"log"
    22  
    23  	"github.com/ethw3/go-ethereuma/node"
    24  )
    25  
    26  // SampleLifecycle is a trivial network service that can be attached to a node for
    27  // life cycle management.
    28  //
    29  // The following methods are needed to implement a node.Lifecycle:
    30  //  - Start() error              - method invoked when the node is ready to start the service
    31  //  - Stop() error               - method invoked when the node terminates the service
    32  type SampleLifecycle struct{}
    33  
    34  func (s *SampleLifecycle) Start() error { fmt.Println("Service starting..."); return nil }
    35  func (s *SampleLifecycle) Stop() error  { fmt.Println("Service stopping..."); return nil }
    36  
    37  func ExampleLifecycle() {
    38  	// Create a network node to run protocols with the default values.
    39  	stack, err := node.New(&node.Config{})
    40  	if err != nil {
    41  		log.Fatalf("Failed to create network node: %v", err)
    42  	}
    43  	defer stack.Close()
    44  
    45  	// Create and register a simple network Lifecycle.
    46  	service := new(SampleLifecycle)
    47  	stack.RegisterLifecycle(service)
    48  
    49  	// Boot up the entire protocol stack, do a restart and terminate
    50  	if err := stack.Start(); err != nil {
    51  		log.Fatalf("Failed to start the protocol stack: %v", err)
    52  	}
    53  	if err := stack.Close(); err != nil {
    54  		log.Fatalf("Failed to stop the protocol stack: %v", err)
    55  	}
    56  	// Output:
    57  	// Service starting...
    58  	// Service stopping...
    59  }