github.com/osrg/gobgp@v2.0.0+incompatible/docs/sources/lib.md (about)

     1  # GoBGP as a Go Native BGP library
     2  
     3  This page explains how to use GoBGP as a Go Native BGP library.
     4  
     5  ## Contents
     6  
     7  - [Basic Example](#basic-example)
     8  
     9  ## Basic Example
    10  
    11  ```go
    12  package main
    13  
    14  import (
    15  	"context"
    16  	"time"
    17  
    18  	"github.com/golang/protobuf/ptypes"
    19  	"github.com/golang/protobuf/ptypes/any"
    20  	api "github.com/osrg/gobgp/api"
    21  	gobgp "github.com/osrg/gobgp/pkg/server"
    22  	log "github.com/sirupsen/logrus"
    23  )
    24  
    25  func main() {
    26  	log.SetLevel(log.DebugLevel)
    27  	s := gobgp.NewBgpServer()
    28  	go s.Serve()
    29  
    30  	// global configuration
    31  	if err := s.StartBgp(context.Background(), &api.StartBgpRequest{
    32  		Global: &api.Global{
    33  			As:         65003,
    34  			RouterId:   "10.0.255.254",
    35  			ListenPort: -1, // gobgp won't listen on tcp:179
    36  		},
    37  	}); err != nil {
    38  		log.Fatal(err)
    39  	}
    40  
    41  	// monitor the change of the peer state
    42  	if err := s.MonitorPeer(context.Background(), &api.MonitorPeerRequest{}, func(p *api.Peer){log.Info(p)}); err != nil {
    43  		log.Fatal(err)
    44  	}
    45  
    46  	// neighbor configuration
    47  	n := &api.Peer{
    48  		Conf: &api.PeerConf{
    49  			NeighborAddress: "172.17.0.2",
    50  			PeerAs:          65002,
    51  		},
    52  	}
    53  
    54  	if err := s.AddPeer(context.Background(), &api.AddPeerRequest{
    55  		Peer: n,
    56  	}); err != nil {
    57  		log.Fatal(err)
    58  	}
    59  
    60  	// add routes
    61  	nlri, _ := ptypes.MarshalAny(&api.IPAddressPrefix{
    62  		Prefix:    "10.0.0.0",
    63  		PrefixLen: 24,
    64  	})
    65  
    66  	a1, _ := ptypes.MarshalAny(&api.OriginAttribute{
    67  		Origin: 0,
    68  	})
    69  	a2, _ := ptypes.MarshalAny(&api.NextHopAttribute{
    70  		NextHop: "10.0.0.1",
    71  	})
    72  	attrs := []*any.Any{a1, a2}
    73  
    74  	_, err := s.AddPath(context.Background(), &api.AddPathRequest{
    75  		Path: &api.Path{
    76  			Family:    &api.Family{Afi: api.Family_AFI_IP, Safi: api.Family_SAFI_UNICAST},
    77  			Nlri:   nlri,
    78  			Pattrs: attrs,
    79  		},
    80  	})
    81  	if err != nil {
    82  		log.Fatal(err)
    83  	}
    84  
    85  	// do something useful here instead of exiting
    86  	time.Sleep(time.Minute * 3)
    87  }
    88  ```