github.com/erda-project/erda-infra@v1.0.10-0.20240327085753-f3a249292aeb/examples/service/caller/provider.go (about)

     1  // Copyright (c) 2021 Terminus, Inc.
     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  package caller
    16  
    17  import (
    18  	"context"
    19  	"time"
    20  
    21  	"github.com/erda-project/erda-infra/base/logs"
    22  	"github.com/erda-project/erda-infra/base/servicehub"
    23  	"github.com/erda-project/erda-infra/examples/service/protocol/pb"
    24  	"github.com/erda-project/erda-infra/pkg/transport"
    25  )
    26  
    27  type config struct {
    28  	Name string `file:"name" default:"recallsong"`
    29  }
    30  
    31  // +provider
    32  type provider struct {
    33  	Cfg     *config
    34  	Log     logs.Logger
    35  	Greeter pb.GreeterServiceServer // remote or local service. this doesn't need to care
    36  }
    37  
    38  // Run this is an optional
    39  func (p *provider) Run(ctx context.Context) error {
    40  	tick := time.NewTicker(3 * time.Second)
    41  	defer tick.Stop()
    42  	for {
    43  		select {
    44  		case <-tick.C:
    45  			header := transport.Header{}
    46  			header.Set("Custom-Header", "Custom-Header-Value")
    47  			resp, err := p.Greeter.SayHello(transport.WithHeader(context.Background(), header), &pb.HelloRequest{
    48  				Name: p.Cfg.Name,
    49  			})
    50  			if err != nil {
    51  				p.Log.Error(err)
    52  			}
    53  			p.Log.Info(resp)
    54  		case <-ctx.Done():
    55  			return nil
    56  		}
    57  	}
    58  }
    59  
    60  func init() {
    61  	servicehub.Register("caller", &servicehub.Spec{
    62  		Services:     []string{},
    63  		Description:  "this is caller example",
    64  		Dependencies: []string{"erda.infra.example.GreeterService"},
    65  		ConfigFunc: func() interface{} {
    66  			return &config{}
    67  		},
    68  		Creator: func() servicehub.Provider {
    69  			return &provider{}
    70  		},
    71  	})
    72  }