github.com/OpsMx/go-app-base@v0.0.24/example_main_test.go (about) 1 // Copyright 2022 OpsMx, 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_test 16 17 import ( 18 "bytes" 19 "context" 20 "flag" 21 "fmt" 22 "log" 23 "os" 24 "os/signal" 25 "syscall" 26 "time" 27 28 "github.com/OpsMx/go-app-base/tracer" 29 "github.com/OpsMx/go-app-base/util" 30 "github.com/OpsMx/go-app-base/version" 31 ) 32 33 const ( 34 appName = "example-app" 35 ) 36 37 var ( 38 // eg, http://localhost:14268/api/traces 39 otlpEndpoint = flag.String("otlp-endpoint", "", "otlp collector endpoint") 40 traceToStdout = flag.Bool("traceToStdout", false, "log traces to stdout") 41 traceRatio = flag.Float64("traceRatio", 0.01, "ratio of traces to create, if incoming request is not traced") 42 showversion = flag.Bool("version", false, "show the version and exit") 43 ) 44 45 func exiter() { 46 time.Sleep(1 * time.Second) 47 err := syscall.Kill(syscall.Getpid(), syscall.SIGINT) 48 if err != nil { 49 log.Fatalf("KILL failed: %v", err) 50 } 51 } 52 53 func Example() { 54 // you would not do this, this is just to make test output match. 55 log.SetFlags(log.Flags() &^ (log.Ldate | log.Ltime)) 56 var buf bytes.Buffer 57 log.SetOutput(&buf) 58 defer func() { 59 log.SetOutput(os.Stderr) 60 fmt.Printf("%s", buf.Bytes()) 61 }() 62 63 log.Printf("%s", version.VersionString()) 64 flag.Parse() 65 if *showversion { 66 os.Exit(0) 67 } 68 69 sigchan := make(chan os.Signal, 1) 70 signal.Notify(sigchan, syscall.SIGTERM, syscall.SIGINT) 71 72 ctx, cancel := context.WithCancel(context.Background()) 73 defer cancel() 74 75 if *otlpEndpoint != "" { 76 *otlpEndpoint = util.GetEnvar("OTLP_HTTP_URL", "") 77 } 78 79 tracerProvider, err := tracer.NewTracerProvider(ctx, *otlpEndpoint, *traceToStdout, version.GitHash(), appName, *traceRatio) 80 util.Check(err) 81 defer tracerProvider.Shutdown(ctx) 82 83 // other stuff here 84 85 // you would not do this... this is just to ensure we exit our test 86 go exiter() 87 88 sig := <-sigchan 89 log.Printf("Exiting cleanly due to a signal: %v", sig) 90 91 // Output: 92 // version: dev, hash: dev, buildType: unknown 93 // Exiting cleanly due to a signal: interrupt 94 }