github.com/cs3org/reva/v2@v2.27.7/pkg/events/example/consumer/consumer.go (about)

     1  // Copyright 2018-2021 CERN
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  //
    15  // In applying this license, CERN does not waive the privileges and immunities
    16  // granted to it by virtue of its status as an Intergovernmental Organization
    17  // or submit itself to any jurisdiction.
    18  
    19  // Package consumer contains an example implementation of an event consumer
    20  package consumer
    21  
    22  import (
    23  	"fmt"
    24  	"log"
    25  
    26  	"github.com/cs3org/reva/v2/pkg/events"
    27  )
    28  
    29  // Example consumes events from the queue
    30  func Example(c events.Consumer) {
    31  	// Step 1 - which group does the consumer belong to?
    32  	// each group will get each event that is emitted, but only one member of the group will get it.
    33  	group := "test-consumer"
    34  
    35  	// Step 2 - which events does the consumer listen too?
    36  	evs := []events.Unmarshaller{
    37  		events.ShareCreated{},
    38  		events.ShareUpdated{},
    39  		events.ShareRemoved{},
    40  		events.ReceivedShareUpdated{},
    41  		events.LinkCreated{},
    42  		events.LinkUpdated{},
    43  		events.LinkRemoved{},
    44  		events.LinkAccessed{},
    45  		events.LinkAccessFailed{},
    46  	}
    47  
    48  	// Step 3 - create event channel
    49  	evChan, err := events.Consume(c, group, evs...)
    50  	if err != nil {
    51  		log.Fatal(err)
    52  	}
    53  
    54  	// Step 4 - listen to events
    55  	for {
    56  		event := <-evChan
    57  
    58  		// best to use type switch to differentiate events
    59  		switch v := event.Event.(type) {
    60  		case events.ShareCreated:
    61  			fmt.Printf("%s) Share created: %+v\n", group, v)
    62  		default:
    63  			fmt.Printf("%s) %T: %+v\n", group, v, v)
    64  		}
    65  	}
    66  
    67  }