github.com/erda-project/erda-infra@v1.0.9/base/servicehub/examples/define/main.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 main
    16  
    17  import (
    18  	"context"
    19  	"os"
    20  	"time"
    21  
    22  	"github.com/erda-project/erda-infra/base/logs"
    23  	"github.com/erda-project/erda-infra/base/servicehub"
    24  )
    25  
    26  // define Represents the definition of provider and provides some information
    27  type define struct{}
    28  
    29  // Declare what services the provider provides
    30  func (d *define) Services() []string { return []string{"hello"} }
    31  
    32  // Describe information about this provider
    33  func (d *define) Description() string { return "hello for example" }
    34  
    35  // Return an instance representing the configuration
    36  func (d *define) Config() interface{} { return &config{} }
    37  
    38  // Return a provider creator
    39  func (d *define) Creator() servicehub.Creator {
    40  	return func() servicehub.Provider {
    41  		return &provider{}
    42  	}
    43  }
    44  
    45  type config struct {
    46  	Message string `file:"message" flag:"msg" default:"hi" desc:"message to show"`
    47  }
    48  
    49  type provider struct {
    50  	Cfg *config
    51  	Log logs.Logger
    52  }
    53  
    54  func (p *provider) Init(ctx servicehub.Context) error {
    55  	p.Log.Info("message: ", p.Cfg.Message)
    56  	return nil
    57  }
    58  
    59  func (p *provider) Run(ctx context.Context) error {
    60  	p.Log.Info("hello provider is running...")
    61  	tick := time.NewTicker(3 * time.Second)
    62  	defer tick.Stop()
    63  	for {
    64  		select {
    65  		case <-tick.C:
    66  			p.Log.Info("do something...")
    67  		case <-ctx.Done():
    68  			return nil
    69  		}
    70  	}
    71  }
    72  
    73  func init() {
    74  	servicehub.RegisterProvider("hello-provider", &define{})
    75  }
    76  
    77  func main() {
    78  	hub := servicehub.New()
    79  	hub.Run("examples", "", os.Args...)
    80  }