git.colasdn.top/newrelic/go-agent@v3.26.0+incompatible/_integrations/nrmicro/example/server/server.go (about)

     1  // Copyright 2020 New Relic Corporation. All rights reserved.
     2  // SPDX-License-Identifier: Apache-2.0
     3  
     4  package main
     5  
     6  import (
     7  	"context"
     8  	"fmt"
     9  	"log"
    10  	"os"
    11  	"time"
    12  
    13  	"github.com/micro/go-micro"
    14  	newrelic "github.com/newrelic/go-agent"
    15  	"github.com/newrelic/go-agent/_integrations/nrmicro"
    16  	proto "github.com/newrelic/go-agent/_integrations/nrmicro/example/proto"
    17  )
    18  
    19  // Greeter is the server struct
    20  type Greeter struct{}
    21  
    22  // Hello is the method on the server being called
    23  func (g *Greeter) Hello(ctx context.Context, req *proto.HelloRequest, rsp *proto.HelloResponse) error {
    24  	name := req.GetName()
    25  	if txn := newrelic.FromContext(ctx); nil != txn {
    26  		txn.AddAttribute("Name", name)
    27  	}
    28  	fmt.Println("Request received from", name)
    29  	rsp.Greeting = "Hello " + name
    30  	return nil
    31  }
    32  
    33  func mustGetEnv(key string) string {
    34  	if val := os.Getenv(key); "" != val {
    35  		return val
    36  	}
    37  	panic(fmt.Sprintf("environment variable %s unset", key))
    38  }
    39  
    40  func main() {
    41  	cfg := newrelic.NewConfig("Micro Server", mustGetEnv("NEW_RELIC_LICENSE_KEY"))
    42  	cfg.Logger = newrelic.NewDebugLogger(os.Stdout)
    43  	app, err := newrelic.NewApplication(cfg)
    44  	if nil != err {
    45  		panic(err)
    46  	}
    47  	err = app.WaitForConnection(10 * time.Second)
    48  	if nil != err {
    49  		panic(err)
    50  	}
    51  	defer app.Shutdown(10 * time.Second)
    52  
    53  	service := micro.NewService(
    54  		micro.Name("greeter"),
    55  		// Add the New Relic middleware which will start a new transaction for
    56  		// each Handler invocation.
    57  		micro.WrapHandler(nrmicro.HandlerWrapper(app)),
    58  	)
    59  
    60  	service.Init()
    61  
    62  	proto.RegisterGreeterHandler(service.Server(), new(Greeter))
    63  
    64  	if err := service.Run(); err != nil {
    65  		log.Fatal(err)
    66  	}
    67  }