node_example_test.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. package node_test
  17. import (
  18. "fmt"
  19. "log"
  20. "github.com/ethereum/go-ethereum/node"
  21. )
  22. // SampleLifecycle is a trivial network service that can be attached to a node for
  23. // life cycle management.
  24. //
  25. // The following methods are needed to implement a node.Lifecycle:
  26. // - Start() error - method invoked when the node is ready to start the service
  27. // - Stop() error - method invoked when the node terminates the service
  28. type SampleLifecycle struct{}
  29. func (s *SampleLifecycle) Start() error { fmt.Println("Service starting..."); return nil }
  30. func (s *SampleLifecycle) Stop() error { fmt.Println("Service stopping..."); return nil }
  31. func ExampleLifecycle() {
  32. // Create a network node to run protocols with the default values.
  33. stack, err := node.New(&node.Config{})
  34. if err != nil {
  35. log.Fatalf("Failed to create network node: %v", err)
  36. }
  37. defer stack.Close()
  38. // Create and register a simple network Lifecycle.
  39. service := new(SampleLifecycle)
  40. stack.RegisterLifecycle(service)
  41. // Boot up the entire protocol stack, do a restart and terminate
  42. if err := stack.Start(); err != nil {
  43. log.Fatalf("Failed to start the protocol stack: %v", err)
  44. }
  45. if err := stack.Close(); err != nil {
  46. log.Fatalf("Failed to stop the protocol stack: %v", err)
  47. }
  48. // Output:
  49. // Service starting...
  50. // Service stopping...
  51. }