github.com/newrelic/go-agent@v3.26.0+incompatible/examples/server-http/main.go (about)

     1  // Copyright 2020 New Relic Corporation. All rights reserved.
     2  // SPDX-License-Identifier: Apache-2.0
     3  
     4  // An application that illustrates Distributed Tracing or Cross Application
     5  // Tracing when using http.Server or similar frameworks.
     6  package main
     7  
     8  import (
     9  	"fmt"
    10  	"io"
    11  	"net/http"
    12  	"os"
    13  	"time"
    14  
    15  	newrelic "github.com/newrelic/go-agent"
    16  )
    17  
    18  type handler struct {
    19  	App newrelic.Application
    20  }
    21  
    22  func (h *handler) ServeHTTP(writer http.ResponseWriter, req *http.Request) {
    23  	// The call to StartTransaction must include the response writer and the
    24  	// request.
    25  	txn := h.App.StartTransaction("server-txn", writer, req)
    26  	defer txn.End()
    27  
    28  	if req.URL.String() == "/segments" {
    29  		defer newrelic.StartSegment(txn, "f1").End()
    30  
    31  		func() {
    32  			defer newrelic.StartSegment(txn, "f2").End()
    33  
    34  			io.WriteString(writer, "segments!")
    35  			time.Sleep(10 * time.Millisecond)
    36  		}()
    37  		time.Sleep(10 * time.Millisecond)
    38  	} else {
    39  		// Transaction.WriteHeader has to be used instead of invoking
    40  		// WriteHeader on the response writer.
    41  		txn.WriteHeader(http.StatusNotFound)
    42  	}
    43  }
    44  
    45  func mustGetEnv(key string) string {
    46  	if val := os.Getenv(key); "" != val {
    47  		return val
    48  	}
    49  	panic(fmt.Sprintf("environment variable %s unset", key))
    50  }
    51  
    52  func makeApplication() (newrelic.Application, error) {
    53  	cfg := newrelic.NewConfig("HTTP Server App", mustGetEnv("NEW_RELIC_LICENSE_KEY"))
    54  	cfg.Logger = newrelic.NewDebugLogger(os.Stdout)
    55  	cfg.DistributedTracer.Enabled = true
    56  	app, err := newrelic.NewApplication(cfg)
    57  
    58  	if nil != err {
    59  		return nil, err
    60  	}
    61  
    62  	// Wait for the application to connect.
    63  	if err = app.WaitForConnection(5 * time.Second); nil != err {
    64  		return nil, err
    65  	}
    66  
    67  	return app, nil
    68  }
    69  
    70  func main() {
    71  
    72  	app, err := makeApplication()
    73  	if nil != err {
    74  		fmt.Println(err)
    75  		os.Exit(1)
    76  	}
    77  
    78  	server := http.Server{
    79  		Addr:    ":8000",
    80  		Handler: &handler{App: app},
    81  	}
    82  
    83  	server.ListenAndServe()
    84  }