github.com/blend/go-sdk@v1.20220411.3/examples/web/tracing/main.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package main
     9  
    10  import (
    11  	"github.com/blend/go-sdk/graceful"
    12  	"github.com/blend/go-sdk/logger"
    13  	"github.com/blend/go-sdk/web"
    14  )
    15  
    16  // ShimTracer is a basic tracer.
    17  type ShimTracer struct {
    18  	OnStart  func(*web.Ctx)
    19  	OnFinish func(*web.Ctx, error)
    20  }
    21  
    22  // Start begins the trace.
    23  func (st ShimTracer) Start(ctx *web.Ctx) web.TraceFinisher {
    24  	if st.OnStart != nil {
    25  		st.OnStart(ctx)
    26  	}
    27  	return &ShimTraceFinisher{parent: &st}
    28  }
    29  
    30  // ShimTraceFinisher finishes the traces.
    31  type ShimTraceFinisher struct {
    32  	parent *ShimTracer
    33  }
    34  
    35  // Finish closes the trace.
    36  func (stf ShimTraceFinisher) Finish(ctx *web.Ctx, err error) {
    37  	stf.parent.OnFinish(ctx, err)
    38  }
    39  
    40  func main() {
    41  	log := logger.All()
    42  
    43  	app := web.MustNew(
    44  		web.OptBindAddr(":8080"),
    45  		web.OptLog(log),
    46  		web.OptTracer(ShimTracer{
    47  			OnStart:  func(_ *web.Ctx) { log.Infof("Trace Started") },
    48  			OnFinish: func(_ *web.Ctx, _ error) { log.Infof("Trace Finished") },
    49  		}),
    50  	)
    51  	app.GET("/", func(r *web.Ctx) web.Result {
    52  		return web.Text.Result("ok!")
    53  	})
    54  
    55  	if err := graceful.Shutdown(app); err != nil {
    56  		logger.FatalExit(err)
    57  	}
    58  }