node_example_test.go 2.09 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
// Copyright 2015 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

package node_test

import (
	"fmt"
	"log"

	"github.com/ethereum/go-ethereum/node"
)

26
// SampleLifecycle is a trivial network service that can be attached to a node for
27 28
// life cycle management.
//
29
// The following methods are needed to implement a node.Lifecycle:
30 31
//   - Start() error              - method invoked when the node is ready to start the service
//   - Stop() error               - method invoked when the node terminates the service
32
type SampleLifecycle struct{}
33

34 35
func (s *SampleLifecycle) Start() error { fmt.Println("Service starting..."); return nil }
func (s *SampleLifecycle) Stop() error  { fmt.Println("Service stopping..."); return nil }
36

37
func ExampleLifecycle() {
38 39
	// Create a network node to run protocols with the default values.
	stack, err := node.New(&node.Config{})
40 41 42
	if err != nil {
		log.Fatalf("Failed to create network node: %v", err)
	}
43 44
	defer stack.Close()

45 46 47 48
	// Create and register a simple network Lifecycle.
	service := new(SampleLifecycle)
	stack.RegisterLifecycle(service)

49 50 51 52
	// Boot up the entire protocol stack, do a restart and terminate
	if err := stack.Start(); err != nil {
		log.Fatalf("Failed to start the protocol stack: %v", err)
	}
53
	if err := stack.Close(); err != nil {
54 55 56
		log.Fatalf("Failed to stop the protocol stack: %v", err)
	}
	// Output:
57 58
	// Service starting...
	// Service stopping...
59
}