Compare commits
	
		
			55 Commits
		
	
	
		
			v0.2.0
			...
			11b2c2487c
		
	
	| Author | SHA1 | Date | |
|---|---|---|---|
| 11b2c2487c | |||
| c7e42a7544 | |||
| 8d6297a0cb | |||
| 340cf67515 | |||
| f5cb3456b1 | |||
| f0c3bc6b9e | |||
| 00cb0d0421 | |||
| ede5bc92f7 | |||
| 063ff0f1d0 | |||
| 2310ac574c | |||
| cb0c87d200 | |||
| 92e78f533a | |||
| d4c6ecbefd | |||
| e1d58c0094 | |||
| 9cee9037e4 | |||
| 318115690d | |||
| 8b4bb890be | |||
| e841e11168 | |||
| 7c78416948 | |||
| 31fc6dca16 | |||
| 41d539a607 | |||
| a875f0bb22 | |||
| 52752216fd | |||
| 4f0c5fe665 | |||
| 5c26accc34 | |||
| f8279d9653 | |||
| b44b6a331c | |||
| adfedc9239 | |||
| 89f016ed9d | |||
| 7f60a59d42 | |||
| 262f6a4232 | |||
| 4e014d5ea0 | |||
| 3e319b24fd | |||
| f0a699029a | |||
| e178956eef | |||
| c5da5f7887 | |||
| d414754e14 | |||
| 3b3f7f1f8b | |||
| 00c8e2e4fc | |||
| 2cf15a4837 | |||
| 98fba4eac8 | |||
| 5aa5dda111 | |||
| 81676c5404 | |||
| 075902ecd8 | |||
| a83abba4ce | |||
| e11c563c3a | |||
| 96f9213213 | |||
| ae00c64684 | |||
| 004c1b1ee6 | |||
| 861214be5d | |||
| 896225effc | |||
| 06bf7ebca7 | |||
| 15a597de1d | |||
| 56037c4b05 | |||
| 70ba85bf79 | 
							
								
								
									
										29
									
								
								CHANGELOG.md
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										29
									
								
								CHANGELOG.md
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,29 @@
 | 
				
			|||||||
 | 
					# v0.12.1
 | 
				
			||||||
 | 
					* feat: Implement custom OpenTelemetry span name formatting for HTTP requests.
 | 
				
			||||||
 | 
					* refactor: Streamline OpenTelemetry handler integration by removing custom wrapper.
 | 
				
			||||||
 | 
					## v0.12.2
 | 
				
			||||||
 | 
					* chore: Update Go module dependencies, including OpenTelemetry, gRPC Gateway, gRPC, and Protobuf.
 | 
				
			||||||
 | 
					* chore: Add new test suites for logging, OpenTelemetry initialization, gRPC server setup, and HTTP server setup.
 | 
				
			||||||
 | 
					* chore: Enhance configuration loading tests to cover file and environment variable sources.
 | 
				
			||||||
 | 
					* chore: Improve config test comparison robustness using JSON marshaling.
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					# v0.12.0
 | 
				
			||||||
 | 
					* feat: Add support for excluding HTTP request paths from logging using configurable regular expressions.
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					# v0.11.1:
 | 
				
			||||||
 | 
					* docs: Add comprehensive package-level documentation for the `http` package.
 | 
				
			||||||
 | 
					* docs: Improve documentation for the `InitHTTPServer` function.
 | 
				
			||||||
 | 
					* feat: Introduce specific logging for HTTP 204 (No Content) responses, omitting body logging.
 | 
				
			||||||
 | 
					* fix: Enhance error handling and logging for empty or unreadable HTTP response bodies.
 | 
				
			||||||
 | 
					* chore: Refine HTTP response log messages for improved clarity and consistency.
 | 
				
			||||||
 | 
					* docs: Update documentation for the `Flush` method in `LoggingResponseWriter`
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					# v0.11.0:
 | 
				
			||||||
 | 
					*   Updated `github.com/prometheus/client_golang` dependency to v1.23.0.
 | 
				
			||||||
 | 
					*   Updated `google.golang.org/grpc` dependency to v1.74.2.
 | 
				
			||||||
 | 
					*   Added a `replace` directive for `github.com/prometheus/otlptranslator`.
 | 
				
			||||||
 | 
					*   Renamed `initOTEL` function to `InitOTEL` and added a check to prevent re-initialization.
 | 
				
			||||||
 | 
					*   Improved `dummyHealthCheck` to ensure a positive random duration.
 | 
				
			||||||
 | 
					*   Added comprehensive package, struct, and function comments across `pkg/app`, `pkg/config`, `pkg/logging`, `pkg/otel`, `pkg/srv/grpc`, and `pkg/srv/http` for improved clarity.
 | 
				
			||||||
 | 
					*   Corrected typos in `TODO.md` for "implementing" and "support".
 | 
				
			||||||
 | 
					*   Added a new item to `TODO.md` for early OpenTelemetry initialization.
 | 
				
			||||||
							
								
								
									
										17
									
								
								TODO.md
									
									
									
									
									
								
							
							
						
						
									
										17
									
								
								TODO.md
									
									
									
									
									
								
							@@ -1,4 +1,17 @@
 | 
				
			|||||||
# TODO
 | 
					# TODO
 | 
				
			||||||
 | 
					
 | 
				
			||||||
- [ ] Unit tests
 | 
					- [ ] Add ability to initialize OTEL early (before app runs)
 | 
				
			||||||
- [ ] HTTP Logging Middleware
 | 
					- [ ] Spruce up the README
 | 
				
			||||||
 | 
					- [ ] Create generic interface for implementing a service
 | 
				
			||||||
 | 
					- [ ] Create config sample not called demo, so it is more easily reused
 | 
				
			||||||
 | 
					- [ ] Expand config test case to cover GRPC config
 | 
				
			||||||
 | 
					- [ ] Expand tracing
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					## Done
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					- [x] Test and troubleshoot GRPC Gateway support
 | 
				
			||||||
 | 
					- [x] Finish implementing GRPC service support
 | 
				
			||||||
 | 
					- [x] Unit tests
 | 
				
			||||||
 | 
					- [x] Pattern for extending config
 | 
				
			||||||
 | 
					- [x] HTTP Logging Middleware
 | 
				
			||||||
 | 
					- [x] Fix panic with OTEL disabled
 | 
				
			||||||
 
 | 
				
			|||||||
							
								
								
									
										77
									
								
								go.mod
									
									
									
									
									
								
							
							
						
						
									
										77
									
								
								go.mod
									
									
									
									
									
								
							@@ -1,49 +1,64 @@
 | 
				
			|||||||
module gitea.libretechconsulting.com/rmcguire/go-app
 | 
					module gitea.libretechconsulting.com/rmcguire/go-app
 | 
				
			||||||
 | 
					
 | 
				
			||||||
go 1.23.4
 | 
					go 1.24.2
 | 
				
			||||||
 | 
					
 | 
				
			||||||
require (
 | 
					require (
 | 
				
			||||||
 | 
						buf.build/go/protovalidate v0.14.0
 | 
				
			||||||
	github.com/caarlos0/env/v11 v11.3.1
 | 
						github.com/caarlos0/env/v11 v11.3.1
 | 
				
			||||||
	github.com/prometheus/client_golang v1.20.5
 | 
						github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.2
 | 
				
			||||||
	github.com/rs/zerolog v1.33.0
 | 
						github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2
 | 
				
			||||||
	go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.58.0
 | 
						github.com/prometheus/client_golang v1.23.0
 | 
				
			||||||
	go.opentelemetry.io/otel v1.33.0
 | 
						github.com/rs/zerolog v1.34.0
 | 
				
			||||||
	go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.33.0
 | 
						github.com/stretchr/testify v1.11.1
 | 
				
			||||||
	go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.33.0
 | 
						github.com/swaggest/jsonschema-go v0.3.78
 | 
				
			||||||
	go.opentelemetry.io/otel/exporters/prometheus v0.55.0
 | 
						go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.63.0
 | 
				
			||||||
	go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.33.0
 | 
						go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0
 | 
				
			||||||
	go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.33.0
 | 
						go.opentelemetry.io/otel v1.38.0
 | 
				
			||||||
	go.opentelemetry.io/otel/metric v1.33.0
 | 
						go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.38.0
 | 
				
			||||||
	go.opentelemetry.io/otel/sdk v1.33.0
 | 
						go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.38.0
 | 
				
			||||||
	go.opentelemetry.io/otel/sdk/metric v1.33.0
 | 
						go.opentelemetry.io/otel/exporters/prometheus v0.60.0
 | 
				
			||||||
	go.opentelemetry.io/otel/trace v1.33.0
 | 
						go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.38.0
 | 
				
			||||||
 | 
						go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.38.0
 | 
				
			||||||
 | 
						go.opentelemetry.io/otel/metric v1.38.0
 | 
				
			||||||
 | 
						go.opentelemetry.io/otel/sdk v1.38.0
 | 
				
			||||||
 | 
						go.opentelemetry.io/otel/sdk/metric v1.38.0
 | 
				
			||||||
 | 
						go.opentelemetry.io/otel/trace v1.38.0
 | 
				
			||||||
 | 
						google.golang.org/grpc v1.75.0
 | 
				
			||||||
	gopkg.in/yaml.v3 v3.0.1
 | 
						gopkg.in/yaml.v3 v3.0.1
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
require (
 | 
					require (
 | 
				
			||||||
 | 
						buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go v1.36.8-20250717185734-6c6e0d3c608e.1 // indirect
 | 
				
			||||||
 | 
						cel.dev/expr v0.24.0 // indirect
 | 
				
			||||||
 | 
						github.com/antlr4-go/antlr/v4 v4.13.1 // indirect
 | 
				
			||||||
	github.com/beorn7/perks v1.0.1 // indirect
 | 
						github.com/beorn7/perks v1.0.1 // indirect
 | 
				
			||||||
	github.com/cenkalti/backoff/v4 v4.3.0 // indirect
 | 
						github.com/cenkalti/backoff/v5 v5.0.3 // indirect
 | 
				
			||||||
	github.com/cespare/xxhash/v2 v2.3.0 // indirect
 | 
						github.com/cespare/xxhash/v2 v2.3.0 // indirect
 | 
				
			||||||
 | 
						github.com/davecgh/go-spew v1.1.1 // indirect
 | 
				
			||||||
	github.com/felixge/httpsnoop v1.0.4 // indirect
 | 
						github.com/felixge/httpsnoop v1.0.4 // indirect
 | 
				
			||||||
	github.com/go-logr/logr v1.4.2 // indirect
 | 
						github.com/go-logr/logr v1.4.3 // indirect
 | 
				
			||||||
	github.com/go-logr/stdr v1.2.2 // indirect
 | 
						github.com/go-logr/stdr v1.2.2 // indirect
 | 
				
			||||||
 | 
						github.com/google/cel-go v0.26.1 // indirect
 | 
				
			||||||
	github.com/google/uuid v1.6.0 // indirect
 | 
						github.com/google/uuid v1.6.0 // indirect
 | 
				
			||||||
	github.com/grpc-ecosystem/grpc-gateway/v2 v2.25.1 // indirect
 | 
						github.com/grafana/regexp v0.0.0-20240518133315-a468a5bfb3bc // indirect
 | 
				
			||||||
	github.com/klauspost/compress v1.17.11 // indirect
 | 
						github.com/mattn/go-colorable v0.1.14 // indirect
 | 
				
			||||||
	github.com/mattn/go-colorable v0.1.13 // indirect
 | 
					 | 
				
			||||||
	github.com/mattn/go-isatty v0.0.20 // indirect
 | 
						github.com/mattn/go-isatty v0.0.20 // indirect
 | 
				
			||||||
	github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
 | 
						github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
 | 
				
			||||||
	github.com/prometheus/client_model v0.6.1 // indirect
 | 
						github.com/pmezard/go-difflib v1.0.0 // indirect
 | 
				
			||||||
	github.com/prometheus/common v0.61.0 // indirect
 | 
						github.com/prometheus/client_model v0.6.2 // indirect
 | 
				
			||||||
	github.com/prometheus/procfs v0.15.1 // indirect
 | 
						github.com/prometheus/common v0.65.0 // indirect
 | 
				
			||||||
 | 
						github.com/prometheus/otlptranslator v0.0.2 // indirect
 | 
				
			||||||
 | 
						github.com/prometheus/procfs v0.17.0 // indirect
 | 
				
			||||||
 | 
						github.com/stoewer/go-strcase v1.3.1 // indirect
 | 
				
			||||||
 | 
						github.com/swaggest/refl v1.4.0 // indirect
 | 
				
			||||||
	go.opentelemetry.io/auto/sdk v1.1.0 // indirect
 | 
						go.opentelemetry.io/auto/sdk v1.1.0 // indirect
 | 
				
			||||||
	go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.33.0 // indirect
 | 
						go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.38.0 // indirect
 | 
				
			||||||
	go.opentelemetry.io/proto/otlp v1.4.0 // indirect
 | 
						go.opentelemetry.io/proto/otlp v1.7.1 // indirect
 | 
				
			||||||
	golang.org/x/net v0.33.0 // indirect
 | 
						golang.org/x/exp v0.0.0-20250819193227-8b4c13bb791b // indirect
 | 
				
			||||||
	golang.org/x/sys v0.29.0 // indirect
 | 
						golang.org/x/net v0.43.0 // indirect
 | 
				
			||||||
	golang.org/x/text v0.21.0 // indirect
 | 
						golang.org/x/sys v0.35.0 // indirect
 | 
				
			||||||
	google.golang.org/genproto/googleapis/api v0.0.0-20250102185135-69823020774d // indirect
 | 
						golang.org/x/text v0.28.0 // indirect
 | 
				
			||||||
	google.golang.org/genproto/googleapis/rpc v0.0.0-20250102185135-69823020774d // indirect
 | 
						google.golang.org/genproto/googleapis/api v0.0.0-20250826171959-ef028d996bc1 // indirect
 | 
				
			||||||
	google.golang.org/grpc v1.69.2 // indirect
 | 
						google.golang.org/genproto/googleapis/rpc v0.0.0-20250826171959-ef028d996bc1 // indirect
 | 
				
			||||||
	google.golang.org/protobuf v1.36.1 // indirect
 | 
						google.golang.org/protobuf v1.36.8 // indirect
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 
 | 
				
			|||||||
							
								
								
									
										179
									
								
								go.sum
									
									
									
									
									
								
							
							
						
						
									
										179
									
								
								go.sum
									
									
									
									
									
								
							@@ -1,40 +1,62 @@
 | 
				
			|||||||
 | 
					buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go v1.36.8-20250717185734-6c6e0d3c608e.1 h1:sjY1k5uszbIZfv11HO2keV4SLhNA47SabPO886v7Rvo=
 | 
				
			||||||
 | 
					buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go v1.36.8-20250717185734-6c6e0d3c608e.1/go.mod h1:8EQ5GzyGJQ5tEIwMSxCl8RKJYsjCpAwkdcENoioXT6g=
 | 
				
			||||||
 | 
					buf.build/go/protovalidate v0.14.0 h1:kr/rC/no+DtRyYX+8KXLDxNnI1rINz0imk5K44ZpZ3A=
 | 
				
			||||||
 | 
					buf.build/go/protovalidate v0.14.0/go.mod h1:+F/oISho9MO7gJQNYC2VWLzcO1fTPmaTA08SDYJZncA=
 | 
				
			||||||
 | 
					cel.dev/expr v0.24.0 h1:56OvJKSH3hDGL0ml5uSxZmz3/3Pq4tJ+fb1unVLAFcY=
 | 
				
			||||||
 | 
					cel.dev/expr v0.24.0/go.mod h1:hLPLo1W4QUmuYdA72RBX06QTs6MXw941piREPl3Yfiw=
 | 
				
			||||||
 | 
					github.com/antlr4-go/antlr/v4 v4.13.1 h1:SqQKkuVZ+zWkMMNkjy5FZe5mr5WURWnlpmOuzYWrPrQ=
 | 
				
			||||||
 | 
					github.com/antlr4-go/antlr/v4 v4.13.1/go.mod h1:GKmUxMtwp6ZgGwZSva4eWPC5mS6vUAmOABFgjdkM7Nw=
 | 
				
			||||||
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
 | 
					github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
 | 
				
			||||||
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
 | 
					github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
 | 
				
			||||||
 | 
					github.com/bool64/dev v0.2.39 h1:kP8DnMGlWXhGYJEZE/J0l/gVBdbuhoPGL+MJG4QbofE=
 | 
				
			||||||
 | 
					github.com/bool64/dev v0.2.39/go.mod h1:iJbh1y/HkunEPhgebWRNcs8wfGq7sjvJ6W5iabL8ACg=
 | 
				
			||||||
 | 
					github.com/bool64/shared v0.1.5 h1:fp3eUhBsrSjNCQPcSdQqZxxh9bBwrYiZ+zOKFkM0/2E=
 | 
				
			||||||
 | 
					github.com/bool64/shared v0.1.5/go.mod h1:081yz68YC9jeFB3+Bbmno2RFWvGKv1lPKkMP6MHJlPs=
 | 
				
			||||||
github.com/caarlos0/env/v11 v11.3.1 h1:cArPWC15hWmEt+gWk7YBi7lEXTXCvpaSdCiZE2X5mCA=
 | 
					github.com/caarlos0/env/v11 v11.3.1 h1:cArPWC15hWmEt+gWk7YBi7lEXTXCvpaSdCiZE2X5mCA=
 | 
				
			||||||
github.com/caarlos0/env/v11 v11.3.1/go.mod h1:qupehSf/Y0TUTsxKywqRt/vJjN5nz6vauiYEUUr8P4U=
 | 
					github.com/caarlos0/env/v11 v11.3.1/go.mod h1:qupehSf/Y0TUTsxKywqRt/vJjN5nz6vauiYEUUr8P4U=
 | 
				
			||||||
github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=
 | 
					github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
 | 
				
			||||||
github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
 | 
					github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
 | 
				
			||||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
 | 
					github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
 | 
				
			||||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
 | 
					github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
 | 
				
			||||||
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
 | 
					github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
 | 
				
			||||||
 | 
					github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
 | 
				
			||||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
 | 
					github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
 | 
				
			||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
 | 
					github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
 | 
				
			||||||
github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
 | 
					github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
 | 
				
			||||||
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
 | 
					github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
 | 
				
			||||||
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
 | 
					github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
 | 
				
			||||||
github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
 | 
					github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
 | 
				
			||||||
github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
 | 
					github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
 | 
				
			||||||
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
 | 
					github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
 | 
				
			||||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
 | 
					github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
 | 
				
			||||||
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
 | 
					github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
 | 
				
			||||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
 | 
					github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
 | 
				
			||||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
 | 
					github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
 | 
				
			||||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
 | 
					github.com/google/cel-go v0.26.1 h1:iPbVVEdkhTX++hpe3lzSk7D3G3QSYqLGoHOcEio+UXQ=
 | 
				
			||||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
 | 
					github.com/google/cel-go v0.26.1/go.mod h1:A9O8OU9rdvrK5MQyrqfIxo1a0u4g3sF8KB6PUIaryMM=
 | 
				
			||||||
 | 
					github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
 | 
				
			||||||
 | 
					github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
 | 
				
			||||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
 | 
					github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
 | 
				
			||||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
 | 
					github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
 | 
				
			||||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.25.1 h1:VNqngBF40hVlDloBruUehVYC3ArSgIyScOAyMRqBxRg=
 | 
					github.com/grafana/regexp v0.0.0-20240518133315-a468a5bfb3bc h1:GN2Lv3MGO7AS6PrRoT6yV5+wkrOpcszoIsO4+4ds248=
 | 
				
			||||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.25.1/go.mod h1:RBRO7fro65R6tjKzYgLAFo0t1QEXY1Dp+i/bvpRiqiQ=
 | 
					github.com/grafana/regexp v0.0.0-20240518133315-a468a5bfb3bc/go.mod h1:+JKpmjMGhpgPL+rXZ5nsZieVzvarn86asRlBg4uNGnk=
 | 
				
			||||||
github.com/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc=
 | 
					github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.2 h1:sGm2vDRFUrQJO/Veii4h4zG2vvqG6uWNkBHSTqXOZk0=
 | 
				
			||||||
github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0=
 | 
					github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.2/go.mod h1:wd1YpapPLivG6nQgbf7ZkG1hhSOXDhhn4MLTknx2aAc=
 | 
				
			||||||
 | 
					github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2 h1:8Tjv8EJ+pM1xP8mK6egEbD1OgnVTyacbefKhmbLhIhU=
 | 
				
			||||||
 | 
					github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2/go.mod h1:pkJQ2tZHJ0aFOVEEot6oZmaVEZcRme73eIFmhiVuRWs=
 | 
				
			||||||
 | 
					github.com/iancoleman/orderedmap v0.3.0 h1:5cbR2grmZR/DiVt+VJopEhtVs9YGInGIxAoMJn+Ichc=
 | 
				
			||||||
 | 
					github.com/iancoleman/orderedmap v0.3.0/go.mod h1:XuLcCUkdL5owUCQeF2Ue9uuw1EptkJDkXXS7VoV7XGE=
 | 
				
			||||||
 | 
					github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
 | 
				
			||||||
 | 
					github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
 | 
				
			||||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
 | 
					github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
 | 
				
			||||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
 | 
					github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
 | 
				
			||||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
 | 
					github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
 | 
				
			||||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
 | 
					github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
 | 
				
			||||||
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
 | 
					github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
 | 
				
			||||||
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
 | 
					github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
 | 
				
			||||||
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
 | 
					 | 
				
			||||||
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
 | 
					github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
 | 
				
			||||||
 | 
					github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
 | 
				
			||||||
 | 
					github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
 | 
				
			||||||
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
 | 
					github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
 | 
				
			||||||
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
 | 
					github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
 | 
				
			||||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
 | 
					github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
 | 
				
			||||||
@@ -44,70 +66,99 @@ github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8m
 | 
				
			|||||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
 | 
					github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
 | 
				
			||||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
 | 
					github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
 | 
				
			||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
 | 
					github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
 | 
				
			||||||
github.com/prometheus/client_golang v1.20.5 h1:cxppBPuYhUnsO6yo/aoRol4L7q7UFfdm+bR9r+8l63Y=
 | 
					github.com/prometheus/client_golang v1.23.0 h1:ust4zpdl9r4trLY/gSjlm07PuiBq2ynaXXlptpfy8Uc=
 | 
				
			||||||
github.com/prometheus/client_golang v1.20.5/go.mod h1:PIEt8X02hGcP8JWbeHyeZ53Y/jReSnHgO035n//V5WE=
 | 
					github.com/prometheus/client_golang v1.23.0/go.mod h1:i/o0R9ByOnHX0McrTMTyhYvKE4haaf2mW08I+jGAjEE=
 | 
				
			||||||
github.com/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p8ais2e9E=
 | 
					github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
 | 
				
			||||||
github.com/prometheus/client_model v0.6.1/go.mod h1:OrxVMOVHjw3lKMa8+x6HeMGkHMQyHDk9E3jmP2AmGiY=
 | 
					github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
 | 
				
			||||||
github.com/prometheus/common v0.61.0 h1:3gv/GThfX0cV2lpO7gkTUwZru38mxevy90Bj8YFSRQQ=
 | 
					github.com/prometheus/common v0.65.0 h1:QDwzd+G1twt//Kwj/Ww6E9FQq1iVMmODnILtW1t2VzE=
 | 
				
			||||||
github.com/prometheus/common v0.61.0/go.mod h1:zr29OCN/2BsJRaFwG8QOBr41D6kkchKbpeNH7pAjb/s=
 | 
					github.com/prometheus/common v0.65.0/go.mod h1:0gZns+BLRQ3V6NdaerOhMbwwRbNh9hkGINtQAsP5GS8=
 | 
				
			||||||
github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc=
 | 
					github.com/prometheus/otlptranslator v0.0.2 h1:+1CdeLVrRQ6Psmhnobldo0kTp96Rj80DRXRd5OSnMEQ=
 | 
				
			||||||
github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk=
 | 
					github.com/prometheus/otlptranslator v0.0.2/go.mod h1:P8AwMgdD7XEr6QRUJ2QWLpiAZTgTE2UYgjlu3svompI=
 | 
				
			||||||
 | 
					github.com/prometheus/procfs v0.17.0 h1:FuLQ+05u4ZI+SS/w9+BWEM2TXiHKsUQ9TADiRH7DuK0=
 | 
				
			||||||
 | 
					github.com/prometheus/procfs v0.17.0/go.mod h1:oPQLaDAMRbA+u8H5Pbfq+dl3VDAvHxMUOVhe0wYB2zw=
 | 
				
			||||||
github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=
 | 
					github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=
 | 
				
			||||||
github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=
 | 
					github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=
 | 
				
			||||||
github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
 | 
					github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
 | 
				
			||||||
github.com/rs/zerolog v1.33.0 h1:1cU2KZkvPxNyfgEmhHAz/1A9Bz+llsdYzklWFzgp0r8=
 | 
					github.com/rs/zerolog v1.34.0 h1:k43nTLIwcTVQAncfCw4KZ2VY6ukYoZaBPNOE8txlOeY=
 | 
				
			||||||
github.com/rs/zerolog v1.33.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss=
 | 
					github.com/rs/zerolog v1.34.0/go.mod h1:bJsvje4Z08ROH4Nhs5iH600c3IkWhwp44iRc54W6wYQ=
 | 
				
			||||||
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
 | 
					github.com/sergi/go-diff v1.3.1 h1:xkr+Oxo4BOQKmkn/B9eMK0g5Kg/983T9DqqPHwYqD+8=
 | 
				
			||||||
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
 | 
					github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I=
 | 
				
			||||||
 | 
					github.com/stoewer/go-strcase v1.3.1 h1:iS0MdW+kVTxgMoE1LAZyMiYJFKlOzLooE4MxjirtkAs=
 | 
				
			||||||
 | 
					github.com/stoewer/go-strcase v1.3.1/go.mod h1:fAH5hQ5pehh+j3nZfvwdk2RgEgQjAoM8wodgtPmh1xo=
 | 
				
			||||||
 | 
					github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
 | 
				
			||||||
 | 
					github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
 | 
				
			||||||
 | 
					github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
 | 
				
			||||||
 | 
					github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
 | 
				
			||||||
 | 
					github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
 | 
				
			||||||
 | 
					github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
 | 
				
			||||||
 | 
					github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
 | 
				
			||||||
 | 
					github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
 | 
				
			||||||
 | 
					github.com/swaggest/assertjson v1.9.0 h1:dKu0BfJkIxv/xe//mkCrK5yZbs79jL7OVf9Ija7o2xQ=
 | 
				
			||||||
 | 
					github.com/swaggest/assertjson v1.9.0/go.mod h1:b+ZKX2VRiUjxfUIal0HDN85W0nHPAYUbYH5WkkSsFsU=
 | 
				
			||||||
 | 
					github.com/swaggest/jsonschema-go v0.3.78 h1:5+YFQrLxOR8z6CHvgtZc42WRy/Q9zRQQ4HoAxlinlHw=
 | 
				
			||||||
 | 
					github.com/swaggest/jsonschema-go v0.3.78/go.mod h1:4nniXBuE+FIGkOGuidjOINMH7OEqZK3HCSbfDuLRI0g=
 | 
				
			||||||
 | 
					github.com/swaggest/refl v1.4.0 h1:CftOSdTqRqs100xpFOT/Rifss5xBV/CT0S/FN60Xe9k=
 | 
				
			||||||
 | 
					github.com/swaggest/refl v1.4.0/go.mod h1:4uUVFVfPJ0NSX9FPwMPspeHos9wPFlCMGoPRllUbpvA=
 | 
				
			||||||
 | 
					github.com/yudai/gojsondiff v1.0.0 h1:27cbfqXLVEJ1o8I6v3y9lg8Ydm53EKqHXAOMxEGlCOA=
 | 
				
			||||||
 | 
					github.com/yudai/gojsondiff v1.0.0/go.mod h1:AY32+k2cwILAkW1fbgxQ5mUmMiZFgLIV+FBNExI05xg=
 | 
				
			||||||
 | 
					github.com/yudai/golcs v0.0.0-20170316035057-ecda9a501e82 h1:BHyfKlQyqbsFN5p3IfnEUduWvb9is428/nNb5L3U01M=
 | 
				
			||||||
 | 
					github.com/yudai/golcs v0.0.0-20170316035057-ecda9a501e82/go.mod h1:lgjkn3NuSvDfVJdfcVVdX+jpBxNmX4rDAzaS45IcYoM=
 | 
				
			||||||
go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA=
 | 
					go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA=
 | 
				
			||||||
go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A=
 | 
					go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A=
 | 
				
			||||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.58.0 h1:yd02MEjBdJkG3uabWP9apV+OuWRIXGDuJEUJbOHmCFU=
 | 
					go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.63.0 h1:YH4g8lQroajqUwWbq/tr2QX1JFmEXaDLgG+ew9bLMWo=
 | 
				
			||||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.58.0/go.mod h1:umTcuxiv1n/s/S6/c2AT/g2CQ7u5C59sHDNmfSwgz7Q=
 | 
					go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.63.0/go.mod h1:fvPi2qXDqFs8M4B4fmJhE92TyQs9Ydjlg3RvfUp+NbQ=
 | 
				
			||||||
go.opentelemetry.io/otel v1.33.0 h1:/FerN9bax5LoK51X/sI0SVYrjSE0/yUL7DpxW4K3FWw=
 | 
					go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0 h1:RbKq8BG0FI8OiXhBfcRtqqHcZcka+gU3cskNuf05R18=
 | 
				
			||||||
go.opentelemetry.io/otel v1.33.0/go.mod h1:SUUkR6csvUQl+yjReHu5uM3EtVV7MBm5FHKRlNx4I8I=
 | 
					go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0/go.mod h1:h06DGIukJOevXaj/xrNjhi/2098RZzcLTbc0jDAUbsg=
 | 
				
			||||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.33.0 h1:7F29RDmnlqk6B5d+sUqemt8TBfDqxryYW5gX6L74RFA=
 | 
					go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8=
 | 
				
			||||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.33.0/go.mod h1:ZiGDq7xwDMKmWDrN1XsXAj0iC7hns+2DhxBFSncNHSE=
 | 
					go.opentelemetry.io/otel v1.38.0/go.mod h1:zcmtmQ1+YmQM9wrNsTGV/q/uyusom3P8RxwExxkZhjM=
 | 
				
			||||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.33.0 h1:Vh5HayB/0HHfOQA7Ctx69E/Y/DcQSMPpKANYVMQ7fBA=
 | 
					go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.38.0 h1:vl9obrcoWVKp/lwl8tRE33853I8Xru9HFbw/skNeLs8=
 | 
				
			||||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.33.0/go.mod h1:cpgtDBaqD/6ok/UG0jT15/uKjAY8mRA53diogHBg3UI=
 | 
					go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.38.0/go.mod h1:GAXRxmLJcVM3u22IjTg74zWBrRCKq8BnOqUVLodpcpw=
 | 
				
			||||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.33.0 h1:5pojmb1U1AogINhN3SurB+zm/nIcusopeBNp42f45QM=
 | 
					go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.38.0 h1:GqRJVj7UmLjCVyVJ3ZFLdPRmhDUp2zFmQe3RHIOsw24=
 | 
				
			||||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.33.0/go.mod h1:57gTHJSE5S1tqg+EKsLPlTWhpHMsWlVmer+LA926XiA=
 | 
					go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.38.0/go.mod h1:ri3aaHSmCTVYu2AWv44YMauwAQc0aqI9gHKIcSbI1pU=
 | 
				
			||||||
go.opentelemetry.io/otel/exporters/prometheus v0.55.0 h1:sSPw658Lk2NWAv74lkD3B/RSDb+xRFx46GjkrL3VUZo=
 | 
					go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.38.0 h1:lwI4Dc5leUqENgGuQImwLo4WnuXFPetmPpkLi2IrX54=
 | 
				
			||||||
go.opentelemetry.io/otel/exporters/prometheus v0.55.0/go.mod h1:nC00vyCmQixoeaxF6KNyP42II/RHa9UdruK02qBmHvI=
 | 
					go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.38.0/go.mod h1:Kz/oCE7z5wuyhPxsXDuaPteSWqjSBD5YaSdbxZYGbGk=
 | 
				
			||||||
go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.33.0 h1:FiOTYABOX4tdzi8A0+mtzcsTmi6WBOxk66u0f1Mj9Gs=
 | 
					go.opentelemetry.io/otel/exporters/prometheus v0.60.0 h1:cGtQxGvZbnrWdC2GyjZi0PDKVSLWP/Jocix3QWfXtbo=
 | 
				
			||||||
go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.33.0/go.mod h1:xyo5rS8DgzV0Jtsht+LCEMwyiDbjpsxBpWETwFRF0/4=
 | 
					go.opentelemetry.io/otel/exporters/prometheus v0.60.0/go.mod h1:hkd1EekxNo69PTV4OWFGZcKQiIqg0RfuWExcPKFvepk=
 | 
				
			||||||
go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.33.0 h1:W5AWUn/IVe8RFb5pZx1Uh9Laf/4+Qmm4kJL5zPuvR+0=
 | 
					go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.38.0 h1:wm/Q0GAAykXv83wzcKzGGqAnnfLFyFe7RslekZuv+VI=
 | 
				
			||||||
go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.33.0/go.mod h1:mzKxJywMNBdEX8TSJais3NnsVZUaJ+bAy6UxPTng2vk=
 | 
					go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.38.0/go.mod h1:ra3Pa40+oKjvYh+ZD3EdxFZZB0xdMfuileHAm4nNN7w=
 | 
				
			||||||
go.opentelemetry.io/otel/metric v1.33.0 h1:r+JOocAyeRVXD8lZpjdQjzMadVZp2M4WmQ+5WtEnklQ=
 | 
					go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.38.0 h1:kJxSDN4SgWWTjG/hPp3O7LCGLcHXFlvS2/FFOrwL+SE=
 | 
				
			||||||
go.opentelemetry.io/otel/metric v1.33.0/go.mod h1:L9+Fyctbp6HFTddIxClbQkjtubW6O9QS3Ann/M82u6M=
 | 
					go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.38.0/go.mod h1:mgIOzS7iZeKJdeB8/NYHrJ48fdGc71Llo5bJ1J4DWUE=
 | 
				
			||||||
go.opentelemetry.io/otel/sdk v1.33.0 h1:iax7M131HuAm9QkZotNHEfstof92xM+N8sr3uHXc2IM=
 | 
					go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA=
 | 
				
			||||||
go.opentelemetry.io/otel/sdk v1.33.0/go.mod h1:A1Q5oi7/9XaMlIWzPSxLRWOI8nG3FnzHJNbiENQuihM=
 | 
					go.opentelemetry.io/otel/metric v1.38.0/go.mod h1:kB5n/QoRM8YwmUahxvI3bO34eVtQf2i4utNVLr9gEmI=
 | 
				
			||||||
go.opentelemetry.io/otel/sdk/metric v1.33.0 h1:Gs5VK9/WUJhNXZgn8MR6ITatvAmKeIuCtNbsP3JkNqU=
 | 
					go.opentelemetry.io/otel/sdk v1.38.0 h1:l48sr5YbNf2hpCUj/FoGhW9yDkl+Ma+LrVl8qaM5b+E=
 | 
				
			||||||
go.opentelemetry.io/otel/sdk/metric v1.33.0/go.mod h1:dL5ykHZmm1B1nVRk9dDjChwDmt81MjVp3gLkQRwKf/Q=
 | 
					go.opentelemetry.io/otel/sdk v1.38.0/go.mod h1:ghmNdGlVemJI3+ZB5iDEuk4bWA3GkTpW+DOoZMYBVVg=
 | 
				
			||||||
go.opentelemetry.io/otel/trace v1.33.0 h1:cCJuF7LRjUFso9LPnEAHJDB2pqzp+hbO8eu1qqW2d/s=
 | 
					go.opentelemetry.io/otel/sdk/metric v1.38.0 h1:aSH66iL0aZqo//xXzQLYozmWrXxyFkBJ6qT5wthqPoM=
 | 
				
			||||||
go.opentelemetry.io/otel/trace v1.33.0/go.mod h1:uIcdVUZMpTAmz0tI1z04GoVSezK37CbGV4fr1f2nBck=
 | 
					go.opentelemetry.io/otel/sdk/metric v1.38.0/go.mod h1:dg9PBnW9XdQ1Hd6ZnRz689CbtrUp0wMMs9iPcgT9EZA=
 | 
				
			||||||
go.opentelemetry.io/proto/otlp v1.4.0 h1:TA9WRvW6zMwP+Ssb6fLoUIuirti1gGbP28GcKG1jgeg=
 | 
					go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE=
 | 
				
			||||||
go.opentelemetry.io/proto/otlp v1.4.0/go.mod h1:PPBWZIP98o2ElSqI35IHfu7hIhSwvc5N38Jw8pXuGFY=
 | 
					go.opentelemetry.io/otel/trace v1.38.0/go.mod h1:j1P9ivuFsTceSWe1oY+EeW3sc+Pp42sO++GHkg4wwhs=
 | 
				
			||||||
 | 
					go.opentelemetry.io/proto/otlp v1.7.1 h1:gTOMpGDb0WTBOP8JaO72iL3auEZhVmAQg4ipjOVAtj4=
 | 
				
			||||||
 | 
					go.opentelemetry.io/proto/otlp v1.7.1/go.mod h1:b2rVh6rfI/s2pHWNlB7ILJcRALpcNDzKhACevjI+ZnE=
 | 
				
			||||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
 | 
					go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
 | 
				
			||||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
 | 
					go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
 | 
				
			||||||
golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I=
 | 
					golang.org/x/exp v0.0.0-20250819193227-8b4c13bb791b h1:DXr+pvt3nC887026GRP39Ej11UATqWDmWuS99x26cD0=
 | 
				
			||||||
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
 | 
					golang.org/x/exp v0.0.0-20250819193227-8b4c13bb791b/go.mod h1:4QTo5u+SEIbbKW1RacMZq1YEfOBqeXa19JeshGi+zc4=
 | 
				
			||||||
 | 
					golang.org/x/net v0.43.0 h1:lat02VYK2j4aLzMzecihNvTlJNQUq316m2Mr9rnM6YE=
 | 
				
			||||||
 | 
					golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg=
 | 
				
			||||||
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 | 
					golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 | 
				
			||||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 | 
					golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 | 
				
			||||||
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 | 
					golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 | 
				
			||||||
golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU=
 | 
					golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
 | 
				
			||||||
golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
 | 
					golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
 | 
				
			||||||
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
 | 
					golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng=
 | 
				
			||||||
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
 | 
					golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU=
 | 
				
			||||||
google.golang.org/genproto/googleapis/api v0.0.0-20250102185135-69823020774d h1:H8tOf8XM88HvKqLTxe755haY6r1fqqzLbEnfrmLXlSA=
 | 
					gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=
 | 
				
			||||||
google.golang.org/genproto/googleapis/api v0.0.0-20250102185135-69823020774d/go.mod h1:2v7Z7gP2ZUOGsaFyxATQSRoBnKygqVq2Cwnvom7QiqY=
 | 
					gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=
 | 
				
			||||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20250102185135-69823020774d h1:xJJRGY7TJcvIlpSrN3K6LAWgNFUILlO+OMAqtg9aqnw=
 | 
					google.golang.org/genproto/googleapis/api v0.0.0-20250826171959-ef028d996bc1 h1:APHvLLYBhtZvsbnpkfknDZ7NyH4z5+ub/I0u8L3Oz6g=
 | 
				
			||||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20250102185135-69823020774d/go.mod h1:3ENsm/5D1mzDyhpzeRi1NR784I0BcofWBoSc5QqqMK4=
 | 
					google.golang.org/genproto/googleapis/api v0.0.0-20250826171959-ef028d996bc1/go.mod h1:xUjFWUnWDpZ/C0Gu0qloASKFb6f8/QXiiXhSPFsD668=
 | 
				
			||||||
google.golang.org/grpc v1.69.2 h1:U3S9QEtbXC0bYNvRtcoklF3xGtLViumSYxWykJS+7AU=
 | 
					google.golang.org/genproto/googleapis/rpc v0.0.0-20250826171959-ef028d996bc1 h1:pmJpJEvT846VzausCQ5d7KreSROcDqmO388w5YbnltA=
 | 
				
			||||||
google.golang.org/grpc v1.69.2/go.mod h1:vyjdE6jLBI76dgpDojsFGNaHlxdjXN9ghpnd2o7JGZ4=
 | 
					google.golang.org/genproto/googleapis/rpc v0.0.0-20250826171959-ef028d996bc1/go.mod h1:GmFNa4BdJZ2a8G+wCe9Bg3wwThLrJun751XstdJt5Og=
 | 
				
			||||||
google.golang.org/protobuf v1.36.1 h1:yBPeRvTftaleIgM3PZ/WBIZ7XM/eEYAaEyCwvyjq/gk=
 | 
					google.golang.org/grpc v1.75.0 h1:+TW+dqTd2Biwe6KKfhE5JpiYIBWq865PhKGSXiivqt4=
 | 
				
			||||||
google.golang.org/protobuf v1.36.1/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=
 | 
					google.golang.org/grpc v1.75.0/go.mod h1:JtPAzKiq4v1xcAB2hydNlWI2RnF85XXcV0mhKXr2ecQ=
 | 
				
			||||||
 | 
					google.golang.org/protobuf v1.36.8 h1:xHScyCOEuuwZEc6UtSOvPbAT4zRh0xcNRYekJwfqyMc=
 | 
				
			||||||
 | 
					google.golang.org/protobuf v1.36.8/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU=
 | 
				
			||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
 | 
					gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
 | 
				
			||||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
 | 
					gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
 | 
				
			||||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
 | 
					gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
 | 
				
			||||||
 | 
					gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
 | 
				
			||||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
 | 
					gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
 | 
				
			||||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
 | 
					gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -1,93 +0,0 @@
 | 
				
			|||||||
package app
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
import (
 | 
					 | 
				
			||||||
	"context"
 | 
					 | 
				
			||||||
	"errors"
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	"github.com/rs/zerolog"
 | 
					 | 
				
			||||||
	"go.opentelemetry.io/otel/codes"
 | 
					 | 
				
			||||||
	"go.opentelemetry.io/otel/trace"
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	"gitea.libretechconsulting.com/rmcguire/go-app/pkg/config"
 | 
					 | 
				
			||||||
	"gitea.libretechconsulting.com/rmcguire/go-app/pkg/otel"
 | 
					 | 
				
			||||||
	"gitea.libretechconsulting.com/rmcguire/go-app/pkg/srv"
 | 
					 | 
				
			||||||
)
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
type App struct {
 | 
					 | 
				
			||||||
	AppContext    context.Context
 | 
					 | 
				
			||||||
	HTTP          *AppHTTP
 | 
					 | 
				
			||||||
	cfg           *config.AppConfig
 | 
					 | 
				
			||||||
	l             *zerolog.Logger
 | 
					 | 
				
			||||||
	tracer        trace.Tracer
 | 
					 | 
				
			||||||
	shutdownFuncs []shutdownFunc
 | 
					 | 
				
			||||||
	appDone       chan interface{}
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
type AppHTTP struct {
 | 
					 | 
				
			||||||
	Funcs        []srv.HTTPFunc
 | 
					 | 
				
			||||||
	HealthChecks []srv.HealthCheckFunc
 | 
					 | 
				
			||||||
	httpDone     <-chan interface{}
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
type (
 | 
					 | 
				
			||||||
	healthCheckFunc func(context.Context) error
 | 
					 | 
				
			||||||
	shutdownFunc    func(context.Context) error
 | 
					 | 
				
			||||||
)
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
func (a *App) Done() <-chan interface{} {
 | 
					 | 
				
			||||||
	return a.appDone
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
func (a *App) MustRun() {
 | 
					 | 
				
			||||||
	if a.cfg != nil {
 | 
					 | 
				
			||||||
		panic(errors.New("already ran app trying to run"))
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	// Set up app
 | 
					 | 
				
			||||||
	a.cfg = config.MustFromCtx(a.AppContext)
 | 
					 | 
				
			||||||
	a.l = zerolog.Ctx(a.AppContext)
 | 
					 | 
				
			||||||
	a.shutdownFuncs = make([]shutdownFunc, 0)
 | 
					 | 
				
			||||||
	a.appDone = make(chan interface{})
 | 
					 | 
				
			||||||
	a.HTTP.httpDone = make(chan interface{})
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	if len(a.HTTP.Funcs) < 1 {
 | 
					 | 
				
			||||||
		a.l.Warn().Msg("no http funcs provided, only serving health and metrics")
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	// Start OTEL
 | 
					 | 
				
			||||||
	a.initOTEL()
 | 
					 | 
				
			||||||
	var initSpan trace.Span
 | 
					 | 
				
			||||||
	_, initSpan = a.tracer.Start(a.AppContext, "init")
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	// Start HTTP
 | 
					 | 
				
			||||||
	a.initHTTP()
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	// Monitor app lifecycle
 | 
					 | 
				
			||||||
	go a.run()
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	// Startup Complete
 | 
					 | 
				
			||||||
	a.l.Info().
 | 
					 | 
				
			||||||
		Str("name", a.cfg.Name).
 | 
					 | 
				
			||||||
		Str("version", a.cfg.Version).
 | 
					 | 
				
			||||||
		Str("logLevel", a.cfg.Logging.Level).
 | 
					 | 
				
			||||||
		Msg("app initialized")
 | 
					 | 
				
			||||||
	initSpan.SetStatus(codes.Ok, "")
 | 
					 | 
				
			||||||
	initSpan.End()
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
func (a *App) initHTTP() {
 | 
					 | 
				
			||||||
	var httpShutdown shutdownFunc
 | 
					 | 
				
			||||||
	httpShutdown, a.HTTP.httpDone = srv.MustInitHTTPServer(
 | 
					 | 
				
			||||||
		a.AppContext,
 | 
					 | 
				
			||||||
		a.HTTP.Funcs,
 | 
					 | 
				
			||||||
		a.HTTP.HealthChecks...,
 | 
					 | 
				
			||||||
	)
 | 
					 | 
				
			||||||
	a.shutdownFuncs = append(a.shutdownFuncs, httpShutdown)
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
func (a *App) initOTEL() {
 | 
					 | 
				
			||||||
	var otelShutdown shutdownFunc
 | 
					 | 
				
			||||||
	a.AppContext, otelShutdown = otel.Init(a.AppContext)
 | 
					 | 
				
			||||||
	a.shutdownFuncs = append(a.shutdownFuncs, otelShutdown)
 | 
					 | 
				
			||||||
	a.tracer = otel.MustTracerFromCtx(a.AppContext)
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
							
								
								
									
										29
									
								
								pkg/app/app_types.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										29
									
								
								pkg/app/app_types.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,29 @@
 | 
				
			|||||||
 | 
					// Package app provides methods to configure, run, and stop
 | 
				
			||||||
 | 
					// a go-app.
 | 
				
			||||||
 | 
					package app
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"context"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"github.com/rs/zerolog"
 | 
				
			||||||
 | 
						"go.opentelemetry.io/otel/trace"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"gitea.libretechconsulting.com/rmcguire/go-app/pkg/config"
 | 
				
			||||||
 | 
						grpcopts "gitea.libretechconsulting.com/rmcguire/go-app/pkg/srv/grpc/opts"
 | 
				
			||||||
 | 
						httpopts "gitea.libretechconsulting.com/rmcguire/go-app/pkg/srv/http/opts"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// App is the main application struct, holding its context, configurations,
 | 
				
			||||||
 | 
					// and various services like HTTP and gRPC.
 | 
				
			||||||
 | 
					type App struct {
 | 
				
			||||||
 | 
						AppContext    context.Context
 | 
				
			||||||
 | 
						HTTP          *httpopts.AppHTTP
 | 
				
			||||||
 | 
						GRPC          *grpcopts.AppGRPC
 | 
				
			||||||
 | 
						cfg           *config.AppConfig
 | 
				
			||||||
 | 
						l             *zerolog.Logger
 | 
				
			||||||
 | 
						tracer        trace.Tracer
 | 
				
			||||||
 | 
						shutdownFuncs []shutdownFunc
 | 
				
			||||||
 | 
						appDone       chan any
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					type shutdownFunc func(context.Context) error
 | 
				
			||||||
							
								
								
									
										75
									
								
								pkg/app/init.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										75
									
								
								pkg/app/init.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,75 @@
 | 
				
			|||||||
 | 
					package app
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"context"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"go.opentelemetry.io/otel/attribute"
 | 
				
			||||||
 | 
						"go.opentelemetry.io/otel/codes"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"gitea.libretechconsulting.com/rmcguire/go-app/pkg/otel"
 | 
				
			||||||
 | 
						srvgrpc "gitea.libretechconsulting.com/rmcguire/go-app/pkg/srv/grpc"
 | 
				
			||||||
 | 
						grpcopts "gitea.libretechconsulting.com/rmcguire/go-app/pkg/srv/grpc/opts"
 | 
				
			||||||
 | 
						srvhttp "gitea.libretechconsulting.com/rmcguire/go-app/pkg/srv/http"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (a *App) initGRPC(ctx context.Context) error {
 | 
				
			||||||
 | 
						ctx, span := a.tracer.Start(ctx, "init.grpc")
 | 
				
			||||||
 | 
						defer span.End()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						shutdown, doneChan, err := srvgrpc.InitGRPCServer(ctx,
 | 
				
			||||||
 | 
							&grpcopts.GRPCOpts{
 | 
				
			||||||
 | 
								GRPCConfig: a.cfg.GRPC,
 | 
				
			||||||
 | 
								AppGRPC:    a.GRPC,
 | 
				
			||||||
 | 
							})
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							span.RecordError(err)
 | 
				
			||||||
 | 
							span.SetStatus(codes.Error, err.Error())
 | 
				
			||||||
 | 
							return err
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						a.shutdownFuncs = append(a.shutdownFuncs, shutdown)
 | 
				
			||||||
 | 
						a.GRPC.GRPCDone = doneChan
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						span.SetStatus(codes.Ok, "")
 | 
				
			||||||
 | 
						return nil
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (a *App) initHTTP(ctx context.Context) error {
 | 
				
			||||||
 | 
						var err error
 | 
				
			||||||
 | 
						var httpShutdown shutdownFunc
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						_, span := a.tracer.Start(ctx, "init.http")
 | 
				
			||||||
 | 
						defer span.End()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						span.SetAttributes(
 | 
				
			||||||
 | 
							attribute.Int("numHTTPFuncs", len(a.HTTP.Funcs)),
 | 
				
			||||||
 | 
							attribute.Int("numHTTPMiddlewares", len(a.HTTP.Middleware)),
 | 
				
			||||||
 | 
							attribute.Int("numHTTPHealthChecks", len(a.HTTP.HealthChecks)),
 | 
				
			||||||
 | 
						)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						a.HTTP.Ctx = a.AppContext
 | 
				
			||||||
 | 
						httpShutdown, a.HTTP.HTTPDone, err = srvhttp.InitHTTPServer(a.HTTP)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						a.shutdownFuncs = append(a.shutdownFuncs, httpShutdown)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							span.RecordError(err)
 | 
				
			||||||
 | 
							span.SetStatus(codes.Error, err.Error())
 | 
				
			||||||
 | 
						} else {
 | 
				
			||||||
 | 
							span.SetStatus(codes.Ok, "")
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						return err
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (a *App) InitOTEL() {
 | 
				
			||||||
 | 
						if a.tracer != nil {
 | 
				
			||||||
 | 
							a.l.Debug().Msg("superfluous call of already configured app otel")
 | 
				
			||||||
 | 
							return
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						var otelShutdown shutdownFunc
 | 
				
			||||||
 | 
						a.AppContext, otelShutdown = otel.Init(a.AppContext)
 | 
				
			||||||
 | 
						a.shutdownFuncs = append(a.shutdownFuncs, otelShutdown)
 | 
				
			||||||
 | 
						a.tracer = otel.MustTracerFromCtx(a.AppContext)
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
							
								
								
									
										72
									
								
								pkg/app/monitor.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										72
									
								
								pkg/app/monitor.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,72 @@
 | 
				
			|||||||
 | 
					package app
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"context"
 | 
				
			||||||
 | 
						"sync"
 | 
				
			||||||
 | 
						"time"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"go.opentelemetry.io/otel/attribute"
 | 
				
			||||||
 | 
						"go.opentelemetry.io/otel/codes"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// Watches contexts and channels for the
 | 
				
			||||||
 | 
					// app to be finished and calls shutdown once
 | 
				
			||||||
 | 
					// the app is done
 | 
				
			||||||
 | 
					func (a *App) monitor() {
 | 
				
			||||||
 | 
						select {
 | 
				
			||||||
 | 
						case <-a.AppContext.Done():
 | 
				
			||||||
 | 
							a.l.Warn().Str("reason", a.AppContext.Err().Error()).
 | 
				
			||||||
 | 
								Msg("shutting down on context done")
 | 
				
			||||||
 | 
						case <-a.HTTP.HTTPDone: // TODO: return error on this channel
 | 
				
			||||||
 | 
							a.l.Warn().Msg("shutting down early on http server done")
 | 
				
			||||||
 | 
						case err := <-a.GRPC.GRPCDone:
 | 
				
			||||||
 | 
							a.l.Warn().Err(err).Msg("shutting down early on grpc server done")
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						a.Shutdown()     // Run through all shutdown funcs
 | 
				
			||||||
 | 
						a.appDone <- nil // Notify app
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// Shutdown is typically invoked when AppContext is done
 | 
				
			||||||
 | 
					// or Server has exited. Not intended to be called
 | 
				
			||||||
 | 
					// manually
 | 
				
			||||||
 | 
					func (a *App) Shutdown() {
 | 
				
			||||||
 | 
						now := time.Now()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						doneCtx, cncl := context.WithTimeout(context.Background(), 15*time.Second)
 | 
				
			||||||
 | 
						defer func() {
 | 
				
			||||||
 | 
							if doneCtx.Err() == context.DeadlineExceeded {
 | 
				
			||||||
 | 
								a.l.Err(doneCtx.Err()).
 | 
				
			||||||
 | 
									Dur("shutdownTime", time.Since(now)).
 | 
				
			||||||
 | 
									Msg("app shutdown aborted")
 | 
				
			||||||
 | 
							} else {
 | 
				
			||||||
 | 
								a.l.Info().
 | 
				
			||||||
 | 
									Int("shutdownFuncsCalled", len(a.shutdownFuncs)).
 | 
				
			||||||
 | 
									Dur("shutdownTime", time.Since(now)).
 | 
				
			||||||
 | 
									Msg("app shutdown normally")
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
							cncl()
 | 
				
			||||||
 | 
						}()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						doneCtx, span := a.tracer.Start(doneCtx, "shutdown")
 | 
				
			||||||
 | 
						defer span.End()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						span.SetAttributes(attribute.Int("shutdown.funcs", len(a.shutdownFuncs)))
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						var wg sync.WaitGroup
 | 
				
			||||||
 | 
						wg.Add(len(a.shutdownFuncs))
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						for _, f := range a.shutdownFuncs {
 | 
				
			||||||
 | 
							go func() {
 | 
				
			||||||
 | 
								defer wg.Done()
 | 
				
			||||||
 | 
								err := f(doneCtx)
 | 
				
			||||||
 | 
								if err != nil {
 | 
				
			||||||
 | 
									span.SetStatus(codes.Error, "shutdown failed")
 | 
				
			||||||
 | 
									span.RecordError(err)
 | 
				
			||||||
 | 
									a.l.Err(err).Send()
 | 
				
			||||||
 | 
								}
 | 
				
			||||||
 | 
							}()
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						wg.Wait()
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
							
								
								
									
										106
									
								
								pkg/app/run.go
									
									
									
									
									
								
							
							
						
						
									
										106
									
								
								pkg/app/run.go
									
									
									
									
									
								
							@@ -1,67 +1,63 @@
 | 
				
			|||||||
package app
 | 
					package app
 | 
				
			||||||
 | 
					
 | 
				
			||||||
import (
 | 
					import (
 | 
				
			||||||
	"context"
 | 
						"errors"
 | 
				
			||||||
	"sync"
 | 
					 | 
				
			||||||
	"time"
 | 
					 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"github.com/rs/zerolog"
 | 
				
			||||||
	"go.opentelemetry.io/otel/codes"
 | 
						"go.opentelemetry.io/otel/codes"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"gitea.libretechconsulting.com/rmcguire/go-app/pkg/config"
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// Watches contexts and channels for the
 | 
					func (a *App) Done() <-chan any {
 | 
				
			||||||
// app to be finished and calls shutdown once
 | 
						return a.appDone
 | 
				
			||||||
// the app is done
 | 
					 | 
				
			||||||
func (a *App) run() {
 | 
					 | 
				
			||||||
	select {
 | 
					 | 
				
			||||||
	case <-a.AppContext.Done():
 | 
					 | 
				
			||||||
		a.l.Warn().Str("reason", a.AppContext.Err().Error()).
 | 
					 | 
				
			||||||
			Msg("shutting down on context done")
 | 
					 | 
				
			||||||
	case <-a.HTTP.httpDone:
 | 
					 | 
				
			||||||
		a.l.Warn().Msg("shutting down early on http server done")
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
	a.Shutdown()
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	a.appDone <- nil
 | 
					 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// Typically invoked when AppContext is done
 | 
					func (a *App) MustRun() {
 | 
				
			||||||
// or Server has exited. Not intended to be called
 | 
						if a.cfg != nil {
 | 
				
			||||||
// manually
 | 
							panic(errors.New("already ran app trying to run"))
 | 
				
			||||||
func (a *App) Shutdown() {
 | 
						}
 | 
				
			||||||
	now := time.Now()
 | 
					 | 
				
			||||||
 | 
					
 | 
				
			||||||
	doneCtx, cncl := context.WithTimeout(context.Background(), 15*time.Second)
 | 
						// Set up app
 | 
				
			||||||
	defer func() {
 | 
						a.cfg = config.MustFromCtx(a.AppContext)
 | 
				
			||||||
		if doneCtx.Err() == context.DeadlineExceeded {
 | 
						a.l = zerolog.Ctx(a.AppContext)
 | 
				
			||||||
			a.l.Err(doneCtx.Err()).
 | 
						a.shutdownFuncs = make([]shutdownFunc, 0)
 | 
				
			||||||
				Dur("shutdownTime", time.Since(now)).
 | 
						a.appDone = make(chan any)
 | 
				
			||||||
				Msg("app shutdown aborted")
 | 
						a.HTTP.HTTPDone = make(chan any)
 | 
				
			||||||
		} else {
 | 
					
 | 
				
			||||||
 | 
						if !a.cfg.HTTPEnabled() && !a.cfg.GRPCEnabled() {
 | 
				
			||||||
 | 
							panic(errors.New("neither http nor grpc enabled, nothing to do"))
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						if len(a.HTTP.Funcs) < 1 {
 | 
				
			||||||
 | 
							a.l.Warn().Msg("no http funcs provided, only serving health and metrics")
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// Start OTEL
 | 
				
			||||||
 | 
						// Registers a NO-OP provider if not enabled
 | 
				
			||||||
 | 
						a.InitOTEL()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// With OTEL ready, create an init span to track startup
 | 
				
			||||||
 | 
						ctx, initSpan := a.tracer.Start(a.AppContext, "init")
 | 
				
			||||||
 | 
						defer initSpan.End()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// Prepare GRPC first. The GRPC server may update its opts
 | 
				
			||||||
 | 
						// with a prepared GRPC-Gateway runtime.ServeMux if any of its services
 | 
				
			||||||
 | 
						// have added GRPC-Gateway handlers. If present, serve under api path
 | 
				
			||||||
 | 
						a.runGRPC(ctx)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// Second, prepare and run HTTP server, embedding grpc-gateway
 | 
				
			||||||
 | 
						// runtime.ServeMux if set by runGRPC()
 | 
				
			||||||
 | 
						a.runHTTP(ctx)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// Monitor app lifecycle
 | 
				
			||||||
 | 
						go a.monitor()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// Startup Complete
 | 
				
			||||||
	a.l.Info().
 | 
						a.l.Info().
 | 
				
			||||||
				Int("shutdownFuncsCalled", len(a.shutdownFuncs)).
 | 
							Str("name", a.cfg.Name).
 | 
				
			||||||
				Dur("shutdownTime", time.Since(now)).
 | 
							Str("version", a.cfg.Version).
 | 
				
			||||||
				Msg("app shutdown normally")
 | 
							Str("logLevel", a.cfg.Logging.Level).
 | 
				
			||||||
		}
 | 
							Msg("app initialized")
 | 
				
			||||||
		cncl()
 | 
						initSpan.SetStatus(codes.Ok, "")
 | 
				
			||||||
	}()
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	doneCtx, span := a.tracer.Start(doneCtx, "shutdown")
 | 
					 | 
				
			||||||
	defer span.End()
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	var wg sync.WaitGroup
 | 
					 | 
				
			||||||
	wg.Add(len(a.shutdownFuncs))
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	for _, f := range a.shutdownFuncs {
 | 
					 | 
				
			||||||
		go func() {
 | 
					 | 
				
			||||||
			defer wg.Done()
 | 
					 | 
				
			||||||
			err := f(doneCtx)
 | 
					 | 
				
			||||||
			if err != nil {
 | 
					 | 
				
			||||||
				span.SetStatus(codes.Error, "shutdown failed")
 | 
					 | 
				
			||||||
				span.RecordError(err)
 | 
					 | 
				
			||||||
				a.l.Err(err).Send()
 | 
					 | 
				
			||||||
			}
 | 
					 | 
				
			||||||
		}()
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	wg.Wait()
 | 
					 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 
 | 
				
			|||||||
							
								
								
									
										47
									
								
								pkg/app/run_grpc.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										47
									
								
								pkg/app/run_grpc.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,47 @@
 | 
				
			|||||||
 | 
					package app
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"context"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"github.com/rs/zerolog"
 | 
				
			||||||
 | 
						"go.opentelemetry.io/otel/attribute"
 | 
				
			||||||
 | 
						"go.opentelemetry.io/otel/codes"
 | 
				
			||||||
 | 
						"go.opentelemetry.io/otel/trace"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						optsgrpc "gitea.libretechconsulting.com/rmcguire/go-app/pkg/srv/grpc/opts"
 | 
				
			||||||
 | 
						optshttp "gitea.libretechconsulting.com/rmcguire/go-app/pkg/srv/http/opts"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (a *App) runGRPC(ctx context.Context) {
 | 
				
			||||||
 | 
						if a.GRPC == nil {
 | 
				
			||||||
 | 
							a.GRPC = &optsgrpc.AppGRPC{
 | 
				
			||||||
 | 
								GRPCDone: make(chan error),
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						if !a.cfg.GRPCEnabled() {
 | 
				
			||||||
 | 
							zerolog.Ctx(ctx).Info().Msg("skipping disabled GRPC server")
 | 
				
			||||||
 | 
							return
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						span := trace.SpanFromContext(ctx)
 | 
				
			||||||
 | 
						if err := a.initGRPC(ctx); err != nil {
 | 
				
			||||||
 | 
							span.RecordError(err)
 | 
				
			||||||
 | 
							span.SetStatus(codes.Error, err.Error())
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						span.AddEvent("grpc server started")
 | 
				
			||||||
 | 
						span.SetAttributes(attribute.Int("grpc.services", len(a.GRPC.Services)))
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						if a.GRPC.GetGatewayMux() != nil {
 | 
				
			||||||
 | 
							if a.HTTP.Handlers == nil {
 | 
				
			||||||
 | 
								a.HTTP.Handlers = make([]optshttp.HTTPHandler, 0, 1)
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							a.HTTP.Handlers = append(a.HTTP.Handlers, optshttp.HTTPHandler{
 | 
				
			||||||
 | 
								Prefix:      a.cfg.GRPC.GRPCGatewayPath,
 | 
				
			||||||
 | 
								StripPrefix: true,
 | 
				
			||||||
 | 
								Handler:     a.GRPC.GetGatewayMux(),
 | 
				
			||||||
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							span.AddEvent("GRPC Gateway Mux Registered")
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
							
								
								
									
										33
									
								
								pkg/app/run_http.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										33
									
								
								pkg/app/run_http.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,33 @@
 | 
				
			|||||||
 | 
					package app
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"context"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"github.com/rs/zerolog"
 | 
				
			||||||
 | 
						"go.opentelemetry.io/otel/attribute"
 | 
				
			||||||
 | 
						"go.opentelemetry.io/otel/codes"
 | 
				
			||||||
 | 
						"go.opentelemetry.io/otel/trace"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						optshttp "gitea.libretechconsulting.com/rmcguire/go-app/pkg/srv/http/opts"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (a *App) runHTTP(ctx context.Context) {
 | 
				
			||||||
 | 
						if a.HTTP == nil {
 | 
				
			||||||
 | 
							a.HTTP = &optshttp.AppHTTP{
 | 
				
			||||||
 | 
								HTTPDone: make(chan any),
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						if !a.cfg.HTTPEnabled() {
 | 
				
			||||||
 | 
							zerolog.Ctx(ctx).Info().Msg("skipping disabled HTTP Server")
 | 
				
			||||||
 | 
							return
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						span := trace.SpanFromContext(ctx)
 | 
				
			||||||
 | 
						if err := a.initHTTP(ctx); err != nil {
 | 
				
			||||||
 | 
							span.RecordError(err)
 | 
				
			||||||
 | 
							span.SetStatus(codes.Error, err.Error())
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						span.AddEvent("http server started")
 | 
				
			||||||
 | 
						span.SetAttributes(attribute.Int("http.handlers", len(a.HTTP.Funcs)))
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
							
								
								
									
										40
									
								
								pkg/app/schema.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										40
									
								
								pkg/app/schema.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,40 @@
 | 
				
			|||||||
 | 
					package app
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"encoding/json"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						js "github.com/swaggest/jsonschema-go"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// Schema generates json schema for app's config.AppConfig
 | 
				
			||||||
 | 
					func (a *App) Schema() ([]byte, error) {
 | 
				
			||||||
 | 
						r := js.Reflector{}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						s, err := r.Reflect(*a.cfg)
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							return nil, err
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						return json.MarshalIndent(s, "", "  ")
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// CustomSchema generates json schema for custom config
 | 
				
			||||||
 | 
					// which embeds *config.AppConfig into it
 | 
				
			||||||
 | 
					// Panics if no *config.AppConfig is embedded into custom
 | 
				
			||||||
 | 
					// config type
 | 
				
			||||||
 | 
					//
 | 
				
			||||||
 | 
					// See swaggest/jsonschema-go for struct tag docs
 | 
				
			||||||
 | 
					func CustomSchema[T any](target T) ([]byte, error) {
 | 
				
			||||||
 | 
						if err := HasAppConfig(target); err != nil {
 | 
				
			||||||
 | 
							panic(err.Error())
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						r := js.Reflector{}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						s, err := r.Reflect(target)
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							return nil, err
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						return json.MarshalIndent(s, "", "  ")
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
@@ -9,7 +9,7 @@ import (
 | 
				
			|||||||
	"gitea.libretechconsulting.com/rmcguire/go-app/pkg/logging"
 | 
						"gitea.libretechconsulting.com/rmcguire/go-app/pkg/logging"
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// Helper function to return a context loaded up with
 | 
					// MustSetupConfigAndLogging is a helper function to return a context loaded up with
 | 
				
			||||||
// config.AppConfig and a logger
 | 
					// config.AppConfig and a logger
 | 
				
			||||||
func MustSetupConfigAndLogging(ctx context.Context) context.Context {
 | 
					func MustSetupConfigAndLogging(ctx context.Context) context.Context {
 | 
				
			||||||
	ctx, err := config.LoadConfig(ctx)
 | 
						ctx, err := config.LoadConfig(ctx)
 | 
				
			||||||
@@ -23,3 +23,10 @@ func MustSetupConfigAndLogging(ctx context.Context) context.Context {
 | 
				
			|||||||
	zerolog.Ctx(ctx).Trace().Any("config", *cfg).Send()
 | 
						zerolog.Ctx(ctx).Trace().Any("config", *cfg).Send()
 | 
				
			||||||
	return ctx
 | 
						return ctx
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// MustSetupConfigAndLoggingInto will unmarshal config into a custom type
 | 
				
			||||||
 | 
					// Type MUST include *config.AppConfig
 | 
				
			||||||
 | 
					// Stored in context as *config.AppConfig but can be asserted back
 | 
				
			||||||
 | 
					func MustSetupConfigAndLoggingInto[T any](ctx context.Context, into T) (context.Context, T) {
 | 
				
			||||||
 | 
						return ctx, into
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 
 | 
				
			|||||||
							
								
								
									
										107
									
								
								pkg/app/setup_custom.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										107
									
								
								pkg/app/setup_custom.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,107 @@
 | 
				
			|||||||
 | 
					package app
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"context"
 | 
				
			||||||
 | 
						"errors"
 | 
				
			||||||
 | 
						"flag"
 | 
				
			||||||
 | 
						"fmt"
 | 
				
			||||||
 | 
						"os"
 | 
				
			||||||
 | 
						"reflect"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"gopkg.in/yaml.v3"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"gitea.libretechconsulting.com/rmcguire/go-app/pkg/config"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// MustLoadConfigInto is used to unmarshal config and environment into a custom type
 | 
				
			||||||
 | 
					// that overloads *config.AppConfig. Will perform normal env
 | 
				
			||||||
 | 
					// substitutions for AppConfig, but env overrides for custom type
 | 
				
			||||||
 | 
					// are up to the caller.
 | 
				
			||||||
 | 
					func MustLoadConfigInto[T any](ctx context.Context, into T) (context.Context, T) {
 | 
				
			||||||
 | 
						// Step 1: Check our custom type for required *config.AppConfig
 | 
				
			||||||
 | 
						if err := HasAppConfig(into); err != nil {
 | 
				
			||||||
 | 
							panic(err)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// Step 2: Do the normal thing
 | 
				
			||||||
 | 
						ctx = MustSetupConfigAndLogging(ctx)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// Step 3: Extract the config
 | 
				
			||||||
 | 
						cfg := config.MustFromCtx(ctx)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// Step 4: Unmarshal custom config
 | 
				
			||||||
 | 
						configPath := flag.Lookup("config")
 | 
				
			||||||
 | 
						if configPath != nil && configPath.Value.String() != "" {
 | 
				
			||||||
 | 
							file, err := os.Open(configPath.Value.String())
 | 
				
			||||||
 | 
							if err != nil {
 | 
				
			||||||
 | 
								panic(fmt.Errorf("could not open config file: %w", err))
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
							defer file.Close()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							decoder := yaml.NewDecoder(file)
 | 
				
			||||||
 | 
							if err := decoder.Decode(into); err != nil {
 | 
				
			||||||
 | 
								panic(fmt.Errorf("could not decode config file: %w", err))
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// Step 5: Re-apply AppConfig to custom type
 | 
				
			||||||
 | 
						if err := setAppConfig(into, cfg); err != nil {
 | 
				
			||||||
 | 
							panic(err)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// Step 6: Update context, return custom type
 | 
				
			||||||
 | 
						return ctx, into
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func setAppConfig[T any](target T, appConfig *config.AppConfig) error {
 | 
				
			||||||
 | 
						// Ensure target is a pointer to a struct
 | 
				
			||||||
 | 
						v := reflect.ValueOf(target)
 | 
				
			||||||
 | 
						if v.Kind() != reflect.Ptr || v.IsNil() {
 | 
				
			||||||
 | 
							return errors.New("target must be a non-nil pointer to a struct")
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						v = v.Elem() // Dereference the pointer
 | 
				
			||||||
 | 
						if v.Kind() != reflect.Struct {
 | 
				
			||||||
 | 
							return errors.New("target must be a pointer to a struct")
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// Replace *config.AppConfig
 | 
				
			||||||
 | 
						for i := range v.NumField() {
 | 
				
			||||||
 | 
							field := v.Field(i)
 | 
				
			||||||
 | 
							if field.Type() == reflect.TypeOf((*config.AppConfig)(nil)) {
 | 
				
			||||||
 | 
								if !field.CanSet() {
 | 
				
			||||||
 | 
									return fmt.Errorf("field %q cannot be set", v.Type().Field(i).Name)
 | 
				
			||||||
 | 
								}
 | 
				
			||||||
 | 
								field.Set(reflect.ValueOf(appConfig))
 | 
				
			||||||
 | 
								return nil
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						return errors.New("no *config.AppConfig field found in target struct")
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func HasAppConfig[T any](target T) error {
 | 
				
			||||||
 | 
						v := reflect.ValueOf(target)
 | 
				
			||||||
 | 
						if v.Kind() != reflect.Ptr || v.IsNil() {
 | 
				
			||||||
 | 
							return errors.New("target must be a non-nil pointer to a struct")
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						v = v.Elem()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						if v.Kind() != reflect.Struct {
 | 
				
			||||||
 | 
							return errors.New("target must be a pointer to a struct")
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						hasAppConfig := false
 | 
				
			||||||
 | 
						for i := range v.NumField() {
 | 
				
			||||||
 | 
							field := v.Type().Field(i)
 | 
				
			||||||
 | 
							if field.Type == reflect.TypeOf((*config.AppConfig)(nil)) {
 | 
				
			||||||
 | 
								hasAppConfig = true
 | 
				
			||||||
 | 
								break
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						if !hasAppConfig {
 | 
				
			||||||
 | 
							return errors.New("struct does not contain a *config.AppConfig field")
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						return nil
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
@@ -1,3 +1,7 @@
 | 
				
			|||||||
 | 
					// Package config provides types and methods for managing
 | 
				
			||||||
 | 
					// app config. A go-app configuration can be extended by any type
 | 
				
			||||||
 | 
					// that embeds AppConfig, and has helpers to generate json
 | 
				
			||||||
 | 
					// schema merged with the custom type's fields
 | 
				
			||||||
package config
 | 
					package config
 | 
				
			||||||
 | 
					
 | 
				
			||||||
import (
 | 
					import (
 | 
				
			||||||
@@ -6,6 +10,7 @@ import (
 | 
				
			|||||||
	"flag"
 | 
						"flag"
 | 
				
			||||||
	"fmt"
 | 
						"fmt"
 | 
				
			||||||
	"os"
 | 
						"os"
 | 
				
			||||||
 | 
						"regexp"
 | 
				
			||||||
	"runtime/debug"
 | 
						"runtime/debug"
 | 
				
			||||||
	"time"
 | 
						"time"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@@ -13,15 +18,15 @@ import (
 | 
				
			|||||||
	"gopkg.in/yaml.v3"
 | 
						"gopkg.in/yaml.v3"
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// To be set by ldflags in go build command or
 | 
					// Version is to be set by ldflags in go build command or
 | 
				
			||||||
// retrieved from build meta below
 | 
					// retrieved from build meta below.
 | 
				
			||||||
var Version = "(devel)"
 | 
					var Version = "(devel)"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// Calling this will try to load from config if -config is
 | 
					// LoadConfig will try to load from config if -config is
 | 
				
			||||||
// provided as a file, and will apply any environment overrides
 | 
					// provided as a file, and will apply any environment overrides
 | 
				
			||||||
// on-top of configuration defaults.
 | 
					// on-top of configuration defaults.
 | 
				
			||||||
// Config is stored in returned context, and can be retrieved
 | 
					// Config is stored in returned context, and can be retrieved
 | 
				
			||||||
// using config.FromCtx(ctx)
 | 
					// using config.FromCtx(ctx).
 | 
				
			||||||
func LoadConfig(ctx context.Context) (context.Context, error) {
 | 
					func LoadConfig(ctx context.Context) (context.Context, error) {
 | 
				
			||||||
	configPath := flag.String("config", "", "Path to the configuration file")
 | 
						configPath := flag.String("config", "", "Path to the configuration file")
 | 
				
			||||||
	flag.Parse()
 | 
						flag.Parse()
 | 
				
			||||||
@@ -40,6 +45,8 @@ func LoadConfig(ctx context.Context) (context.Context, error) {
 | 
				
			|||||||
	return ctx, nil
 | 
						return ctx, nil
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// loadConfig loads the application configuration from the specified path,
 | 
				
			||||||
 | 
					// applying environment variable overrides.
 | 
				
			||||||
func loadConfig(configPath string) (*AppConfig, error) {
 | 
					func loadConfig(configPath string) (*AppConfig, error) {
 | 
				
			||||||
	cfg := *DefaultConfig
 | 
						cfg := *DefaultConfig
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@@ -69,6 +76,8 @@ func loadConfig(configPath string) (*AppConfig, error) {
 | 
				
			|||||||
	return &cfg, nil
 | 
						return &cfg, nil
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// prepareConfig enriches and validates the AppConfig, parsing duration strings
 | 
				
			||||||
 | 
					// for HTTP timeouts.
 | 
				
			||||||
func prepareConfig(cfg *AppConfig) error {
 | 
					func prepareConfig(cfg *AppConfig) error {
 | 
				
			||||||
	var errs error
 | 
						var errs error
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@@ -97,15 +106,23 @@ func prepareConfig(cfg *AppConfig) error {
 | 
				
			|||||||
		}
 | 
							}
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// Prepare user-provided expressions, panic up-front if invalid
 | 
				
			||||||
 | 
						cfg.HTTP.excludeRegexps = make([]*regexp.Regexp, len(cfg.HTTP.LogExcludePathRegexps))
 | 
				
			||||||
 | 
						for i, re := range cfg.HTTP.LogExcludePathRegexps {
 | 
				
			||||||
 | 
							cfg.HTTP.excludeRegexps[i] = regexp.MustCompile(re)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	return errs
 | 
						return errs
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// Returns read timeout, write timeout, and idle timeout, in that order
 | 
					// Timeouts returns read timeout, write timeout, and idle timeout, in that order.
 | 
				
			||||||
// nil if unset
 | 
					// Returns nil if unset.
 | 
				
			||||||
func (h *HTTPConfig) Timeouts() (*time.Duration, *time.Duration, *time.Duration) {
 | 
					func (h *HTTPConfig) Timeouts() (*time.Duration, *time.Duration, *time.Duration) {
 | 
				
			||||||
	return h.rT, h.wT, h.iT
 | 
						return h.rT, h.wT, h.iT
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// getVersion returns the application version, preferring the build info version
 | 
				
			||||||
 | 
					// over the compile-time set Version variable.
 | 
				
			||||||
func getVersion() string {
 | 
					func getVersion() string {
 | 
				
			||||||
	if info, ok := debug.ReadBuildInfo(); ok && info.Main.Version != "(devel)" {
 | 
						if info, ok := debug.ReadBuildInfo(); ok && info.Main.Version != "(devel)" {
 | 
				
			||||||
		return info.Main.Version
 | 
							return info.Main.Version
 | 
				
			||||||
 
 | 
				
			|||||||
							
								
								
									
										191
									
								
								pkg/config/config_test.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										191
									
								
								pkg/config/config_test.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,191 @@
 | 
				
			|||||||
 | 
					package config
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"encoding/json"
 | 
				
			||||||
 | 
						"os"
 | 
				
			||||||
 | 
						"testing"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// Changing defaults could be a breaking change,
 | 
				
			||||||
 | 
					// if this needs to be modified to pass the test,
 | 
				
			||||||
 | 
					// an item should be added to the changelog.
 | 
				
			||||||
 | 
					//
 | 
				
			||||||
 | 
					// This should be maintained, as it is the primary
 | 
				
			||||||
 | 
					// interface between an app and the app framework.
 | 
				
			||||||
 | 
					var testDefaultConfig = &AppConfig{
 | 
				
			||||||
 | 
						Environment: "development",
 | 
				
			||||||
 | 
						Version:     getVersion(),
 | 
				
			||||||
 | 
						Logging: &LogConfig{
 | 
				
			||||||
 | 
							Enabled:    true,
 | 
				
			||||||
 | 
							Level:      "info",
 | 
				
			||||||
 | 
							Format:     LogFormatJSON,
 | 
				
			||||||
 | 
							Output:     "stderr",
 | 
				
			||||||
 | 
							TimeFormat: TimeFormatLong,
 | 
				
			||||||
 | 
						},
 | 
				
			||||||
 | 
						HTTP: &HTTPConfig{
 | 
				
			||||||
 | 
							Enabled:      true,
 | 
				
			||||||
 | 
							Listen:       "127.0.0.1:8080",
 | 
				
			||||||
 | 
							LogRequests:  false,
 | 
				
			||||||
 | 
							ReadTimeout:  "10s",
 | 
				
			||||||
 | 
							WriteTimeout: "10s",
 | 
				
			||||||
 | 
							IdleTimeout:  "1m",
 | 
				
			||||||
 | 
						},
 | 
				
			||||||
 | 
						GRPC: &GRPCConfig{
 | 
				
			||||||
 | 
							Enabled:               false,
 | 
				
			||||||
 | 
							Listen:                "127.0.0.1:8081",
 | 
				
			||||||
 | 
							LogRequests:           false,
 | 
				
			||||||
 | 
							EnableReflection:      true,
 | 
				
			||||||
 | 
							EnableInstrumentation: true,
 | 
				
			||||||
 | 
						},
 | 
				
			||||||
 | 
						OTEL: &OTELConfig{
 | 
				
			||||||
 | 
							Enabled:            true,
 | 
				
			||||||
 | 
							PrometheusEnabled:  true,
 | 
				
			||||||
 | 
							PrometheusPath:     "/metrics",
 | 
				
			||||||
 | 
							StdoutEnabled:      false,
 | 
				
			||||||
 | 
							MetricIntervalSecs: 30,
 | 
				
			||||||
 | 
						},
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func Test_loadConfig(t *testing.T) {
 | 
				
			||||||
 | 
						type args struct {
 | 
				
			||||||
 | 
							configPath string
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						tests := []struct {
 | 
				
			||||||
 | 
							name    string
 | 
				
			||||||
 | 
							args    args
 | 
				
			||||||
 | 
							want    *AppConfig
 | 
				
			||||||
 | 
							wantErr bool
 | 
				
			||||||
 | 
						}{
 | 
				
			||||||
 | 
							{
 | 
				
			||||||
 | 
								name:    "Ensure defaults",
 | 
				
			||||||
 | 
								args:    args{configPath: ""},
 | 
				
			||||||
 | 
								want:    testDefaultConfig,
 | 
				
			||||||
 | 
								wantErr: false,
 | 
				
			||||||
 | 
							},
 | 
				
			||||||
 | 
							{
 | 
				
			||||||
 | 
								name: "Load from file",
 | 
				
			||||||
 | 
								args: args{configPath: "./testdata/config.yaml"},
 | 
				
			||||||
 | 
								want: &AppConfig{
 | 
				
			||||||
 | 
									Name:        "test-app",
 | 
				
			||||||
 | 
									Environment: "development",
 | 
				
			||||||
 | 
									Version:     getVersion(),
 | 
				
			||||||
 | 
									Logging: &LogConfig{
 | 
				
			||||||
 | 
										Enabled:    true,
 | 
				
			||||||
 | 
										Level:      "debug",
 | 
				
			||||||
 | 
										Format:     LogFormatJSON,
 | 
				
			||||||
 | 
										Output:     "stderr",
 | 
				
			||||||
 | 
										TimeFormat: TimeFormatLong,
 | 
				
			||||||
 | 
									},
 | 
				
			||||||
 | 
									HTTP: &HTTPConfig{
 | 
				
			||||||
 | 
										Enabled:      true,
 | 
				
			||||||
 | 
										Listen:       "127.0.0.1:9090",
 | 
				
			||||||
 | 
										LogRequests:  false,
 | 
				
			||||||
 | 
										ReadTimeout:  "10s",
 | 
				
			||||||
 | 
										WriteTimeout: "10s",
 | 
				
			||||||
 | 
										IdleTimeout:  "1m",
 | 
				
			||||||
 | 
									},
 | 
				
			||||||
 | 
									GRPC: &GRPCConfig{
 | 
				
			||||||
 | 
										Enabled:               false,
 | 
				
			||||||
 | 
										Listen:                "127.0.0.1:8081",
 | 
				
			||||||
 | 
										LogRequests:           false,
 | 
				
			||||||
 | 
										EnableReflection:      true,
 | 
				
			||||||
 | 
										EnableInstrumentation: true,
 | 
				
			||||||
 | 
									},
 | 
				
			||||||
 | 
									OTEL: &OTELConfig{
 | 
				
			||||||
 | 
										Enabled:            true,
 | 
				
			||||||
 | 
										PrometheusEnabled:  true,
 | 
				
			||||||
 | 
										PrometheusPath:     "/metrics",
 | 
				
			||||||
 | 
										StdoutEnabled:      false,
 | 
				
			||||||
 | 
										MetricIntervalSecs: 30,
 | 
				
			||||||
 | 
									},
 | 
				
			||||||
 | 
								},
 | 
				
			||||||
 | 
							},
 | 
				
			||||||
 | 
							{
 | 
				
			||||||
 | 
								name: "Load from env",
 | 
				
			||||||
 | 
								args: args{configPath: ""},
 | 
				
			||||||
 | 
								want: &AppConfig{
 | 
				
			||||||
 | 
									Name:        "test-app-env",
 | 
				
			||||||
 | 
									Environment: "production",
 | 
				
			||||||
 | 
									Version:     getVersion(),
 | 
				
			||||||
 | 
									Logging: &LogConfig{
 | 
				
			||||||
 | 
										Enabled:    false,
 | 
				
			||||||
 | 
										Level:      "error",
 | 
				
			||||||
 | 
										Format:     LogFormatConsole,
 | 
				
			||||||
 | 
										Output:     "stdout",
 | 
				
			||||||
 | 
										TimeFormat: TimeFormatUnix,
 | 
				
			||||||
 | 
									},
 | 
				
			||||||
 | 
									HTTP: &HTTPConfig{
 | 
				
			||||||
 | 
										Enabled:      false,
 | 
				
			||||||
 | 
										Listen:       "0.0.0.0:80",
 | 
				
			||||||
 | 
										LogRequests:  true,
 | 
				
			||||||
 | 
										ReadTimeout:  "15s",
 | 
				
			||||||
 | 
										WriteTimeout: "15s",
 | 
				
			||||||
 | 
										IdleTimeout:  "2m",
 | 
				
			||||||
 | 
									},
 | 
				
			||||||
 | 
									GRPC: &GRPCConfig{
 | 
				
			||||||
 | 
										Enabled:               true,
 | 
				
			||||||
 | 
										Listen:                "0.0.0.0:443",
 | 
				
			||||||
 | 
										LogRequests:           true,
 | 
				
			||||||
 | 
										EnableReflection:      false,
 | 
				
			||||||
 | 
										EnableInstrumentation: false,
 | 
				
			||||||
 | 
									},
 | 
				
			||||||
 | 
									OTEL: &OTELConfig{
 | 
				
			||||||
 | 
										Enabled:            false,
 | 
				
			||||||
 | 
										PrometheusEnabled:  false,
 | 
				
			||||||
 | 
										PrometheusPath:     "/metricsz",
 | 
				
			||||||
 | 
										StdoutEnabled:      true,
 | 
				
			||||||
 | 
										MetricIntervalSecs: 60,
 | 
				
			||||||
 | 
									},
 | 
				
			||||||
 | 
								},
 | 
				
			||||||
 | 
							},
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						for _, tt := range tests {
 | 
				
			||||||
 | 
							t.Run(tt.name, func(t *testing.T) {
 | 
				
			||||||
 | 
								if tt.name == "Load from env" {
 | 
				
			||||||
 | 
									os.Setenv("APP_NAME", "test-app-env")
 | 
				
			||||||
 | 
									os.Setenv("APP_ENVIRONMENT", "production")
 | 
				
			||||||
 | 
									os.Setenv("APP_LOG_ENABLED", "false")
 | 
				
			||||||
 | 
									os.Setenv("APP_LOG_LEVEL", "error")
 | 
				
			||||||
 | 
									os.Setenv("APP_LOG_FORMAT", "console")
 | 
				
			||||||
 | 
									os.Setenv("APP_LOG_OUTPUT", "stdout")
 | 
				
			||||||
 | 
									os.Setenv("APP_LOG_TIME_FORMAT", "unix")
 | 
				
			||||||
 | 
									os.Setenv("APP_HTTP_ENABLED", "false")
 | 
				
			||||||
 | 
									os.Setenv("APP_HTTP_LISTEN", "0.0.0.0:80")
 | 
				
			||||||
 | 
									os.Setenv("APP_HTTP_LOG_REQUESTS", "true")
 | 
				
			||||||
 | 
									os.Setenv("APP_HTTP_READ_TIMEOUT", "15s")
 | 
				
			||||||
 | 
									os.Setenv("APP_HTTP_WRITE_TIMEOUT", "15s")
 | 
				
			||||||
 | 
									os.Setenv("APP_HTTP_IDLE_TIMEOUT", "2m")
 | 
				
			||||||
 | 
									os.Setenv("APP_GRPC_ENABLED", "true")
 | 
				
			||||||
 | 
									os.Setenv("APP_GRPC_LISTEN", "0.0.0.0:443")
 | 
				
			||||||
 | 
									os.Setenv("APP_GRPC_LOG_REQUESTS", "true")
 | 
				
			||||||
 | 
									os.Setenv("APP_GRPC_ENABLE_REFLECTION", "false")
 | 
				
			||||||
 | 
									os.Setenv("APP_GRPC_ENABLE_INSTRUMENTATION", "false")
 | 
				
			||||||
 | 
									os.Setenv("APP_OTEL_ENABLED", "false")
 | 
				
			||||||
 | 
									os.Setenv("APP_OTEL_PROMETHEUS_ENABLED", "false")
 | 
				
			||||||
 | 
									os.Setenv("APP_OTEL_PROMETHEUS_PATH", "/metricsz")
 | 
				
			||||||
 | 
									os.Setenv("APP_OTEL_STDOUT_ENABLED", "true")
 | 
				
			||||||
 | 
									os.Setenv("APP_OTEL_METRIC_INTERVAL_SECS", "60")
 | 
				
			||||||
 | 
								}
 | 
				
			||||||
 | 
								got, err := loadConfig(tt.args.configPath)
 | 
				
			||||||
 | 
								if (err != nil) != tt.wantErr {
 | 
				
			||||||
 | 
									t.Errorf("loadConfig() error = %v, wantErr %v", err, tt.wantErr)
 | 
				
			||||||
 | 
									return
 | 
				
			||||||
 | 
								}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
								// Marshal both the expected and actual structs to JSON
 | 
				
			||||||
 | 
								gotJSON, err := json.Marshal(got)
 | 
				
			||||||
 | 
								if err != nil {
 | 
				
			||||||
 | 
									t.Fatalf("Failed to marshal got to JSON: %v", err)
 | 
				
			||||||
 | 
								}
 | 
				
			||||||
 | 
								wantJSON, err := json.Marshal(tt.want)
 | 
				
			||||||
 | 
								if err != nil {
 | 
				
			||||||
 | 
									t.Fatalf("Failed to marshal want to JSON: %v", err)
 | 
				
			||||||
 | 
								}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
								// Compare the JSON strings
 | 
				
			||||||
 | 
								if string(gotJSON) != string(wantJSON) {
 | 
				
			||||||
 | 
									t.Errorf("loadConfig() JSON = %s, want JSON = %s", string(gotJSON), string(wantJSON))
 | 
				
			||||||
 | 
								}
 | 
				
			||||||
 | 
							})
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
@@ -9,10 +9,12 @@ type appConfigKey uint8
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
const appConfigCtxKey appConfigKey = iota
 | 
					const appConfigCtxKey appConfigKey = iota
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func (a *AppConfig) AddToCtx(ctx context.Context) context.Context {
 | 
					// AddToCtx adds the AppConfig to the provided context.
 | 
				
			||||||
	return context.WithValue(ctx, appConfigCtxKey, a)
 | 
					func (ac *AppConfig) AddToCtx(ctx context.Context) context.Context {
 | 
				
			||||||
 | 
						return context.WithValue(ctx, appConfigCtxKey, ac)
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// MustFromCtx retrieves the AppConfig from the context, or panics if not found.
 | 
				
			||||||
func MustFromCtx(ctx context.Context) *AppConfig {
 | 
					func MustFromCtx(ctx context.Context) *AppConfig {
 | 
				
			||||||
	cfg, err := FromCtx(ctx)
 | 
						cfg, err := FromCtx(ctx)
 | 
				
			||||||
	if err != nil {
 | 
						if err != nil {
 | 
				
			||||||
@@ -21,6 +23,7 @@ func MustFromCtx(ctx context.Context) *AppConfig {
 | 
				
			|||||||
	return cfg
 | 
						return cfg
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// FromCtx retrieves the AppConfig from the context.
 | 
				
			||||||
func FromCtx(ctx context.Context) (*AppConfig, error) {
 | 
					func FromCtx(ctx context.Context) (*AppConfig, error) {
 | 
				
			||||||
	ctxData := ctx.Value(appConfigCtxKey)
 | 
						ctxData := ctx.Value(appConfigCtxKey)
 | 
				
			||||||
	if ctxData == nil {
 | 
						if ctxData == nil {
 | 
				
			||||||
 
 | 
				
			|||||||
							
								
								
									
										43
									
								
								pkg/config/ctx_test.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										43
									
								
								pkg/config/ctx_test.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,43 @@
 | 
				
			|||||||
 | 
					package config
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"context"
 | 
				
			||||||
 | 
						"testing"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func TestFromCtx(t *testing.T) {
 | 
				
			||||||
 | 
						app := &AppConfig{
 | 
				
			||||||
 | 
							Name: "testapp",
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						appCtx := app.AddToCtx(context.Background())
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						type args struct {
 | 
				
			||||||
 | 
							ctx context.Context
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						tests := []struct {
 | 
				
			||||||
 | 
							name    string
 | 
				
			||||||
 | 
							args    args
 | 
				
			||||||
 | 
							wantErr bool
 | 
				
			||||||
 | 
						}{
 | 
				
			||||||
 | 
							{
 | 
				
			||||||
 | 
								name:    "Unprepared app context",
 | 
				
			||||||
 | 
								args:    args{ctx: context.Background()},
 | 
				
			||||||
 | 
								wantErr: true,
 | 
				
			||||||
 | 
							},
 | 
				
			||||||
 | 
							{
 | 
				
			||||||
 | 
								name:    "Prepared app context",
 | 
				
			||||||
 | 
								args:    args{ctx: appCtx},
 | 
				
			||||||
 | 
								wantErr: false,
 | 
				
			||||||
 | 
							},
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						for _, tt := range tests {
 | 
				
			||||||
 | 
							t.Run(tt.name, func(t *testing.T) {
 | 
				
			||||||
 | 
								_, err := FromCtx(tt.args.ctx)
 | 
				
			||||||
 | 
								if (err != nil) != tt.wantErr {
 | 
				
			||||||
 | 
									t.Errorf("FromCtx() error = %v, wantErr %v", err, tt.wantErr)
 | 
				
			||||||
 | 
									return
 | 
				
			||||||
 | 
								}
 | 
				
			||||||
 | 
							})
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
							
								
								
									
										5
									
								
								pkg/config/testdata/config.yaml
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										5
									
								
								pkg/config/testdata/config.yaml
									
									
									
									
										vendored
									
									
										Normal file
									
								
							@@ -0,0 +1,5 @@
 | 
				
			|||||||
 | 
					name: test-app
 | 
				
			||||||
 | 
					logging:
 | 
				
			||||||
 | 
					  level: debug
 | 
				
			||||||
 | 
					http:
 | 
				
			||||||
 | 
					  listen: "127.0.0.1:9090"
 | 
				
			||||||
@@ -1,96 +1,48 @@
 | 
				
			|||||||
package config
 | 
					package config
 | 
				
			||||||
 | 
					
 | 
				
			||||||
import "time"
 | 
					// DefaultConfig provides a default application configuration.
 | 
				
			||||||
 | 
					 | 
				
			||||||
// Default Settings
 | 
					 | 
				
			||||||
var DefaultConfig = &AppConfig{
 | 
					var DefaultConfig = &AppConfig{
 | 
				
			||||||
	Environment: "development",
 | 
						Environment: "development",
 | 
				
			||||||
	Version:     getVersion(),
 | 
						Version:     getVersion(),
 | 
				
			||||||
	Logging: &LogConfig{
 | 
						Logging:     defaultLoggingConfig,
 | 
				
			||||||
		Enabled:    true,
 | 
						HTTP:        defaultHTTPConfig,
 | 
				
			||||||
		Level:      "info",
 | 
						OTEL:        defaultOTELConfig,
 | 
				
			||||||
		Format:     LogFormatJSON,
 | 
						GRPC:        defaultGRPCConfig,
 | 
				
			||||||
		Output:     "stderr",
 | 
					 | 
				
			||||||
		TimeFormat: TimeFormatLong,
 | 
					 | 
				
			||||||
	},
 | 
					 | 
				
			||||||
	HTTP: &HTTPConfig{
 | 
					 | 
				
			||||||
		Listen:       "127.0.0.1:8080",
 | 
					 | 
				
			||||||
		LogRequests:  false,
 | 
					 | 
				
			||||||
		ReadTimeout:  "10s",
 | 
					 | 
				
			||||||
		WriteTimeout: "10s",
 | 
					 | 
				
			||||||
		IdleTimeout:  "1m",
 | 
					 | 
				
			||||||
	},
 | 
					 | 
				
			||||||
	OTEL: &OTELConfig{
 | 
					 | 
				
			||||||
		Enabled:            true,
 | 
					 | 
				
			||||||
		PrometheusEnabled:  true,
 | 
					 | 
				
			||||||
		PrometheusPath:     "/metrics",
 | 
					 | 
				
			||||||
		StdoutEnabled:      false,
 | 
					 | 
				
			||||||
		MetricIntervalSecs: 30,
 | 
					 | 
				
			||||||
	},
 | 
					 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
type AppConfig struct {
 | 
					type AppConfig struct {
 | 
				
			||||||
	Name        string `yaml:"name,omitempty" env:"APP_NAME"`
 | 
						Name        string `yaml:"name,omitempty" env:"APP_NAME" json:"name,omitempty"`
 | 
				
			||||||
	Environment string `yaml:"environment,omitempty" env:"APP_ENVIRONMENT"`
 | 
						Environment string `yaml:"environment,omitempty" env:"APP_ENVIRONMENT" json:"environment,omitempty"`
 | 
				
			||||||
	// This should either be set by ldflags, such as with
 | 
						// This should either be set by ldflags, such as with
 | 
				
			||||||
	// go build -ldflags "-X gitea.libretechconsulting.com/rmcguire/go-app/pkg/config.Version=$(VERSION)"
 | 
						// go build -ldflags "-X gitea.libretechconsulting.com/rmcguire/go-app/pkg/config.Version=$(VERSION)"
 | 
				
			||||||
	// or allow this to use build meta. Will default to (devel)
 | 
						// or allow this to use build meta. Will default to (devel)
 | 
				
			||||||
	Version string      `yaml:"version,omitempty" env:"APP_VERSION"`
 | 
						Version string      `yaml:"version,omitempty" env:"APP_VERSION" json:"version,omitempty"`
 | 
				
			||||||
	Logging *LogConfig  `yaml:"logging,omitempty"`
 | 
						Logging *LogConfig  `yaml:"logging,omitempty" json:"logging,omitempty"`
 | 
				
			||||||
	HTTP    *HTTPConfig `yaml:"http,omitempty"`
 | 
						HTTP    *HTTPConfig `yaml:"http,omitempty" json:"http,omitempty"`
 | 
				
			||||||
	OTEL    *OTELConfig `yaml:"otel,omitempty"`
 | 
						OTEL    *OTELConfig `yaml:"otel,omitempty" json:"otel,omitempty"`
 | 
				
			||||||
 | 
						GRPC    *GRPCConfig `yaml:"grpc,omitempty" json:"grpc,omitempty"`
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// Logging Configuration
 | 
					// HTTPEnabled returns true if HTTP is enabled in the AppConfig.
 | 
				
			||||||
type LogConfig struct {
 | 
					func (ac *AppConfig) HTTPEnabled() bool {
 | 
				
			||||||
	Enabled    bool       `yaml:"enabled,omitempty" env:"APP_LOG_ENABLED"`
 | 
						if ac.HTTP != nil && ac.HTTP.Enabled {
 | 
				
			||||||
	Level      string     `yaml:"level,omitempty" env:"APP_LOG_LEVEL"`
 | 
							return true
 | 
				
			||||||
	Format     LogFormat  `yaml:"format,omitempty" env:"APP_LOG_FORMAT"`
 | 
						}
 | 
				
			||||||
	Output     LogOutput  `yaml:"output,omitempty" env:"APP_LOG_OUTPUT"`
 | 
						return false
 | 
				
			||||||
	TimeFormat TimeFormat `yaml:"timeFormat,omitempty" env:"APP_LOG_TIME_FORMAT"`
 | 
					 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
type LogFormat string
 | 
					// GRPCEnabled returns true if gRPC is enabled in the AppConfig.
 | 
				
			||||||
 | 
					func (ac *AppConfig) GRPCEnabled() bool {
 | 
				
			||||||
const (
 | 
						if ac.GRPC != nil && ac.GRPC.Enabled {
 | 
				
			||||||
	LogFormatConsole LogFormat = "console"
 | 
							return true
 | 
				
			||||||
	LogFormatJSON    LogFormat = "json"
 | 
						}
 | 
				
			||||||
)
 | 
						return false
 | 
				
			||||||
 | 
					 | 
				
			||||||
type TimeFormat string
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
const (
 | 
					 | 
				
			||||||
	TimeFormatShort   TimeFormat = "short"
 | 
					 | 
				
			||||||
	TimeFormatLong    TimeFormat = "long"
 | 
					 | 
				
			||||||
	TimeFormatUnix    TimeFormat = "unix"
 | 
					 | 
				
			||||||
	TimeFormatRFC3339 TimeFormat = "rfc3339"
 | 
					 | 
				
			||||||
	TimeFormatOff     TimeFormat = "off"
 | 
					 | 
				
			||||||
)
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
type LogOutput string
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
const (
 | 
					 | 
				
			||||||
	LogOutputStdout LogOutput = "stdout"
 | 
					 | 
				
			||||||
	LogOutputStderr LogOutput = "stderr"
 | 
					 | 
				
			||||||
)
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
// HTTP Configuration
 | 
					 | 
				
			||||||
type HTTPConfig struct {
 | 
					 | 
				
			||||||
	Listen       string `yaml:"listen,omitempty" env:"APP_HTTP_LISTEN"`
 | 
					 | 
				
			||||||
	LogRequests  bool   `yaml:"logRequests" env:"APP_HTTP_LOG_REQUESTS"`
 | 
					 | 
				
			||||||
	ReadTimeout  string `yaml:"readTimeout" env:"APP_HTTP_READ_TIMEOUT"`   // Go duration (e.g. 10s)
 | 
					 | 
				
			||||||
	WriteTimeout string `yaml:"writeTimeout" env:"APP_HTTP_WRITE_TIMEOUT"` // Go duration (e.g. 10s)
 | 
					 | 
				
			||||||
	IdleTimeout  string `yaml:"idleTimeout" env:"APP_HTTP_IDLE_TIMEOUT"`   // Go duration (e.g. 10s)
 | 
					 | 
				
			||||||
	rT           *time.Duration
 | 
					 | 
				
			||||||
	wT           *time.Duration
 | 
					 | 
				
			||||||
	iT           *time.Duration
 | 
					 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// OTEL Configuration
 | 
					// OTELEnabled returns true if OpenTelemetry is enabled in the AppConfig.
 | 
				
			||||||
type OTELConfig struct {
 | 
					func (ac *AppConfig) OTELEnabled() bool {
 | 
				
			||||||
	Enabled            bool   `yaml:"enabled,omitempty" env:"APP_OTEL_ENABLED"`
 | 
						if ac.OTEL != nil && ac.OTEL.Enabled {
 | 
				
			||||||
	PrometheusEnabled  bool   `yaml:"prometheusEnabled,omitempty" env:"APP_OTEL_PROMETHEUS_ENABLED"`
 | 
							return true
 | 
				
			||||||
	PrometheusPath     string `yaml:"prometheusPath,omitempty" env:"APP_OTEL_PROMETHEUS_PATH"`
 | 
						}
 | 
				
			||||||
	StdoutEnabled      bool   `yaml:"stdoutEnabled,omitempty" env:"APP_OTEL_STDOUT_ENABLED"`
 | 
						return false
 | 
				
			||||||
	MetricIntervalSecs int    `yaml:"metricIntervalSecs,omitempty" env:"APP_OTEL_METRIC_INTERVAL_SECS"`
 | 
					 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 
 | 
				
			|||||||
							
								
								
									
										21
									
								
								pkg/config/types_grpc.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										21
									
								
								pkg/config/types_grpc.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,21 @@
 | 
				
			|||||||
 | 
					package config
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					var defaultGRPCConfig = &GRPCConfig{
 | 
				
			||||||
 | 
						Enabled: false,
 | 
				
			||||||
 | 
						Listen:  "127.0.0.1:8081",
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						LogRequests:           false,
 | 
				
			||||||
 | 
						EnableReflection:      true,
 | 
				
			||||||
 | 
						EnableInstrumentation: true,
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					type GRPCConfig struct {
 | 
				
			||||||
 | 
						Enabled               bool   `yaml:"enabled" env:"APP_GRPC_ENABLED" json:"enabled,omitempty"`
 | 
				
			||||||
 | 
						Listen                string `yaml:"listen" env:"APP_GRPC_LISTEN" json:"listen,omitempty"`
 | 
				
			||||||
 | 
						LogRequests           bool   `yaml:"logRequests" env:"APP_GRPC_LOG_REQUESTS" json:"logRequests,omitempty"`
 | 
				
			||||||
 | 
						EnableProtovalidate   bool   `yaml:"enableProtovalidate" env:"APP_GRPC_ENABLE_PROTOVALIDATE" json:"enableProtovalidate,omitempty" default:"false" description:"Add a chain unary and streaming interceptor for buf.build/go/protovalidate"`
 | 
				
			||||||
 | 
						EnableReflection      bool   `yaml:"enableReflection" env:"APP_GRPC_ENABLE_REFLECTION" json:"enableReflection,omitempty"`
 | 
				
			||||||
 | 
						EnableInstrumentation bool   `yaml:"enableInstrumentation" env:"APP_GRPC_ENABLE_INSTRUMENTATION" json:"enableInstrumentation,omitempty"` // requires OTEL
 | 
				
			||||||
 | 
						EnableGRPCGateway     bool   `yaml:"enableGRPCGateway" json:"enableGRPCGateway,omitempty" env:"APP_GRPC_ENABLE_GATEWAY" default:"true"`
 | 
				
			||||||
 | 
						GRPCGatewayPath       string `yaml:"grpcGatewayPath" json:"grpcGatewayPath,omitempty" env:"APP_GRPC_GATEWAY_PATH" default:"/grpc-api"`
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
							
								
								
									
										40
									
								
								pkg/config/types_http.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										40
									
								
								pkg/config/types_http.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,40 @@
 | 
				
			|||||||
 | 
					package config
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"regexp"
 | 
				
			||||||
 | 
						"sync"
 | 
				
			||||||
 | 
						"time"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					var defaultHTTPConfig = &HTTPConfig{
 | 
				
			||||||
 | 
						Enabled: true,
 | 
				
			||||||
 | 
						Listen:  "127.0.0.1:8080",
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						LogRequests:  false,
 | 
				
			||||||
 | 
						ReadTimeout:  "10s",
 | 
				
			||||||
 | 
						WriteTimeout: "10s",
 | 
				
			||||||
 | 
						IdleTimeout:  "1m",
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// HTTPConfig provides HTTP server Configuration
 | 
				
			||||||
 | 
					type HTTPConfig struct {
 | 
				
			||||||
 | 
						Enabled               bool     `yaml:"enabled" env:"APP_HTTP_ENABLED" json:"enabled,omitempty"`
 | 
				
			||||||
 | 
						Listen                string   `yaml:"listen,omitempty" env:"APP_HTTP_LISTEN" json:"listen,omitempty"`
 | 
				
			||||||
 | 
						LogRequests           bool     `yaml:"logRequests" env:"APP_HTTP_LOG_REQUESTS" json:"logRequests,omitempty"`
 | 
				
			||||||
 | 
						LogExcludePathRegexps []string `yaml:"logExcludePathRegexps" env:"APP_HTTP_LOG_EXCLUDE_PATH_REGEXPS" json:"logExcludePathRegexps,omitempty"`
 | 
				
			||||||
 | 
						ReadTimeout           string   `yaml:"readTimeout" env:"APP_HTTP_READ_TIMEOUT" json:"readTimeout,omitempty"`    // Go duration (e.g. 10s)
 | 
				
			||||||
 | 
						WriteTimeout          string   `yaml:"writeTimeout" env:"APP_HTTP_WRITE_TIMEOUT" json:"writeTimeout,omitempty"` // Go duration (e.g. 10s)
 | 
				
			||||||
 | 
						IdleTimeout           string   `yaml:"idleTimeout" env:"APP_HTTP_IDLE_TIMEOUT" json:"idleTimeout,omitempty"`    // Go duration (e.g. 10s)
 | 
				
			||||||
 | 
						excludeRegexps        []*regexp.Regexp
 | 
				
			||||||
 | 
						rT                    *time.Duration
 | 
				
			||||||
 | 
						wT                    *time.Duration
 | 
				
			||||||
 | 
						iT                    *time.Duration
 | 
				
			||||||
 | 
						lock                  sync.RWMutex
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (h *HTTPConfig) GetExcludeRegexps() []*regexp.Regexp {
 | 
				
			||||||
 | 
						h.lock.RLock()
 | 
				
			||||||
 | 
						defer h.lock.RUnlock()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						return h.excludeRegexps
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
							
								
								
									
										42
									
								
								pkg/config/types_logging.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										42
									
								
								pkg/config/types_logging.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,42 @@
 | 
				
			|||||||
 | 
					package config
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					var defaultLoggingConfig = &LogConfig{
 | 
				
			||||||
 | 
						Enabled:    true,
 | 
				
			||||||
 | 
						Level:      "info",
 | 
				
			||||||
 | 
						Format:     LogFormatJSON,
 | 
				
			||||||
 | 
						Output:     "stderr",
 | 
				
			||||||
 | 
						TimeFormat: TimeFormatLong,
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// LogConfig provides Logging Configuration
 | 
				
			||||||
 | 
					type LogConfig struct {
 | 
				
			||||||
 | 
						Enabled    bool       `yaml:"enabled,omitempty" env:"APP_LOG_ENABLED" json:"enabled,omitempty"`
 | 
				
			||||||
 | 
						Level      string     `yaml:"level,omitempty" env:"APP_LOG_LEVEL" json:"level,omitempty"`
 | 
				
			||||||
 | 
						Format     LogFormat  `yaml:"format,omitempty" env:"APP_LOG_FORMAT" json:"format,omitempty"`
 | 
				
			||||||
 | 
						Output     LogOutput  `yaml:"output,omitempty" env:"APP_LOG_OUTPUT" json:"output,omitempty"`
 | 
				
			||||||
 | 
						TimeFormat TimeFormat `yaml:"timeFormat,omitempty" env:"APP_LOG_TIME_FORMAT" json:"timeFormat,omitempty"`
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					type LogFormat string
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					const (
 | 
				
			||||||
 | 
						LogFormatConsole LogFormat = "console"
 | 
				
			||||||
 | 
						LogFormatJSON    LogFormat = "json"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					type TimeFormat string
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					const (
 | 
				
			||||||
 | 
						TimeFormatShort   TimeFormat = "short"
 | 
				
			||||||
 | 
						TimeFormatLong    TimeFormat = "long"
 | 
				
			||||||
 | 
						TimeFormatUnix    TimeFormat = "unix"
 | 
				
			||||||
 | 
						TimeFormatRFC3339 TimeFormat = "rfc3339"
 | 
				
			||||||
 | 
						TimeFormatOff     TimeFormat = "off"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					type LogOutput string
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					const (
 | 
				
			||||||
 | 
						LogOutputStdout LogOutput = "stdout"
 | 
				
			||||||
 | 
						LogOutputStderr LogOutput = "stderr"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
							
								
								
									
										18
									
								
								pkg/config/types_otel.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										18
									
								
								pkg/config/types_otel.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,18 @@
 | 
				
			|||||||
 | 
					package config
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					var defaultOTELConfig = &OTELConfig{
 | 
				
			||||||
 | 
						Enabled:            true,
 | 
				
			||||||
 | 
						PrometheusEnabled:  true,
 | 
				
			||||||
 | 
						PrometheusPath:     "/metrics",
 | 
				
			||||||
 | 
						StdoutEnabled:      false,
 | 
				
			||||||
 | 
						MetricIntervalSecs: 30,
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// OtelConfig provides OTEL Configuration
 | 
				
			||||||
 | 
					type OTELConfig struct {
 | 
				
			||||||
 | 
						Enabled            bool   `yaml:"enabled,omitempty" env:"APP_OTEL_ENABLED" json:"enabled,omitempty"`
 | 
				
			||||||
 | 
						PrometheusEnabled  bool   `yaml:"prometheusEnabled,omitempty" env:"APP_OTEL_PROMETHEUS_ENABLED" json:"prometheusEnabled,omitempty"`
 | 
				
			||||||
 | 
						PrometheusPath     string `yaml:"prometheusPath,omitempty" env:"APP_OTEL_PROMETHEUS_PATH" json:"prometheusPath,omitempty"`
 | 
				
			||||||
 | 
						StdoutEnabled      bool   `yaml:"stdoutEnabled,omitempty" env:"APP_OTEL_STDOUT_ENABLED" json:"stdoutEnabled,omitempty"`
 | 
				
			||||||
 | 
						MetricIntervalSecs int    `yaml:"metricIntervalSecs,omitempty" env:"APP_OTEL_METRIC_INTERVAL_SECS" json:"metricIntervalSecs,omitempty"`
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
@@ -1,3 +1,5 @@
 | 
				
			|||||||
 | 
					// Package logging provides a centralized logging utility using zerolog,
 | 
				
			||||||
 | 
					// with configurable output formats and log levels.
 | 
				
			||||||
package logging
 | 
					package logging
 | 
				
			||||||
 | 
					
 | 
				
			||||||
import (
 | 
					import (
 | 
				
			||||||
@@ -38,7 +40,7 @@ func configureLogger(cfg *config.LogConfig) (*zerolog.Logger, error) {
 | 
				
			|||||||
			TimeFormat: zerolog.TimeFieldFormat,
 | 
								TimeFormat: zerolog.TimeFieldFormat,
 | 
				
			||||||
		}
 | 
							}
 | 
				
			||||||
		if cfg.TimeFormat == config.TimeFormatOff {
 | 
							if cfg.TimeFormat == config.TimeFormatOff {
 | 
				
			||||||
			consoleWriter.FormatTimestamp = func(_ interface{}) string {
 | 
								consoleWriter.FormatTimestamp = func(_ any) string {
 | 
				
			||||||
				return ""
 | 
									return ""
 | 
				
			||||||
			}
 | 
								}
 | 
				
			||||||
		}
 | 
							}
 | 
				
			||||||
 
 | 
				
			|||||||
							
								
								
									
										133
									
								
								pkg/logging/logging_test.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										133
									
								
								pkg/logging/logging_test.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,133 @@
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
 | 
					package logging
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"bytes"
 | 
				
			||||||
 | 
						"context"
 | 
				
			||||||
 | 
						"encoding/json"
 | 
				
			||||||
 | 
						"io"
 | 
				
			||||||
 | 
						"os"
 | 
				
			||||||
 | 
						"testing"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"github.com/rs/zerolog"
 | 
				
			||||||
 | 
						"github.com/stretchr/testify/assert"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"gitea.libretechconsulting.com/rmcguire/go-app/pkg/config"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func TestMustInitLogging(t *testing.T) {
 | 
				
			||||||
 | 
						cfg := &config.AppConfig{
 | 
				
			||||||
 | 
							Logging: &config.LogConfig{
 | 
				
			||||||
 | 
								Level:  "info",
 | 
				
			||||||
 | 
								Format: "json",
 | 
				
			||||||
 | 
							},
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						ctx := cfg.AddToCtx(context.Background())
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						ctx = MustInitLogging(ctx)
 | 
				
			||||||
 | 
						logger := zerolog.Ctx(ctx)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						assert.NotNil(t, logger)
 | 
				
			||||||
 | 
						assert.Equal(t, zerolog.InfoLevel, logger.GetLevel())
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func TestConfigureLogger(t *testing.T) {
 | 
				
			||||||
 | 
						type args struct {
 | 
				
			||||||
 | 
							cfg *config.LogConfig
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						tests := []struct {
 | 
				
			||||||
 | 
							name      string
 | 
				
			||||||
 | 
							args      args
 | 
				
			||||||
 | 
							level     zerolog.Level
 | 
				
			||||||
 | 
							wantJSON  bool
 | 
				
			||||||
 | 
							wantTime  bool
 | 
				
			||||||
 | 
							assertion func(t *testing.T, output string)
 | 
				
			||||||
 | 
						}{
 | 
				
			||||||
 | 
							{
 | 
				
			||||||
 | 
								name: "json logger",
 | 
				
			||||||
 | 
								args: args{
 | 
				
			||||||
 | 
									cfg: &config.LogConfig{
 | 
				
			||||||
 | 
										Level:  "debug",
 | 
				
			||||||
 | 
										Format: "json",
 | 
				
			||||||
 | 
									},
 | 
				
			||||||
 | 
								},
 | 
				
			||||||
 | 
								level:    zerolog.DebugLevel,
 | 
				
			||||||
 | 
								wantJSON: true,
 | 
				
			||||||
 | 
							},
 | 
				
			||||||
 | 
							{
 | 
				
			||||||
 | 
								name: "console logger",
 | 
				
			||||||
 | 
								args: args{
 | 
				
			||||||
 | 
									cfg: &config.LogConfig{
 | 
				
			||||||
 | 
										Level:  "warn",
 | 
				
			||||||
 | 
										Format: "console",
 | 
				
			||||||
 | 
									},
 | 
				
			||||||
 | 
								},
 | 
				
			||||||
 | 
								level:    zerolog.WarnLevel,
 | 
				
			||||||
 | 
								wantJSON: false,
 | 
				
			||||||
 | 
							},
 | 
				
			||||||
 | 
							{
 | 
				
			||||||
 | 
								name: "with time",
 | 
				
			||||||
 | 
								args: args{
 | 
				
			||||||
 | 
									cfg: &config.LogConfig{
 | 
				
			||||||
 | 
										Level:      "info",
 | 
				
			||||||
 | 
										Format:     "json",
 | 
				
			||||||
 | 
										TimeFormat: "unix",
 | 
				
			||||||
 | 
									},
 | 
				
			||||||
 | 
								},
 | 
				
			||||||
 | 
								level:    zerolog.InfoLevel,
 | 
				
			||||||
 | 
								wantJSON: true,
 | 
				
			||||||
 | 
								wantTime: true,
 | 
				
			||||||
 | 
								assertion: func(t *testing.T, output string) {
 | 
				
			||||||
 | 
									var log map[string]interface{}
 | 
				
			||||||
 | 
									err := json.Unmarshal([]byte(output), &log)
 | 
				
			||||||
 | 
									assert.NoError(t, err)
 | 
				
			||||||
 | 
									assert.Contains(t, log, "time")
 | 
				
			||||||
 | 
								},
 | 
				
			||||||
 | 
							},
 | 
				
			||||||
 | 
							{
 | 
				
			||||||
 | 
								name: "without time",
 | 
				
			||||||
 | 
								args: args{
 | 
				
			||||||
 | 
									cfg: &config.LogConfig{
 | 
				
			||||||
 | 
										Level:      "info",
 | 
				
			||||||
 | 
										Format:     "json",
 | 
				
			||||||
 | 
										TimeFormat: "off",
 | 
				
			||||||
 | 
									},
 | 
				
			||||||
 | 
								},
 | 
				
			||||||
 | 
								level:    zerolog.InfoLevel,
 | 
				
			||||||
 | 
								wantJSON: true,
 | 
				
			||||||
 | 
								wantTime: false,
 | 
				
			||||||
 | 
								assertion: func(t *testing.T, output string) {
 | 
				
			||||||
 | 
									var log map[string]interface{}
 | 
				
			||||||
 | 
									err := json.Unmarshal([]byte(output), &log)
 | 
				
			||||||
 | 
									assert.NoError(t, err)
 | 
				
			||||||
 | 
									assert.NotContains(t, log, "time")
 | 
				
			||||||
 | 
								},
 | 
				
			||||||
 | 
							},
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						for _, tt := range tests {
 | 
				
			||||||
 | 
							t.Run(tt.name, func(t *testing.T) {
 | 
				
			||||||
 | 
								// Capture output
 | 
				
			||||||
 | 
								old := os.Stderr
 | 
				
			||||||
 | 
								r, w, _ := os.Pipe()
 | 
				
			||||||
 | 
								os.Stderr = w
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
								logger, err := configureLogger(tt.args.cfg)
 | 
				
			||||||
 | 
								assert.NoError(t, err)
 | 
				
			||||||
 | 
								assert.Equal(t, tt.level, logger.GetLevel())
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
								logger.Info().Msg("test")
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
								w.Close()
 | 
				
			||||||
 | 
								os.Stderr = old
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
								var buf bytes.Buffer
 | 
				
			||||||
 | 
								io.Copy(&buf, r)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
								output := buf.String()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
								if tt.assertion != nil {
 | 
				
			||||||
 | 
									tt.assertion(t, output)
 | 
				
			||||||
 | 
								}
 | 
				
			||||||
 | 
							})
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
@@ -1,3 +1,4 @@
 | 
				
			|||||||
 | 
					// Package otel provides OpenTelemetry initialization and configuration for tracing and metrics.
 | 
				
			||||||
package otel
 | 
					package otel
 | 
				
			||||||
 | 
					
 | 
				
			||||||
import (
 | 
					import (
 | 
				
			||||||
@@ -8,6 +9,7 @@ import (
 | 
				
			|||||||
	"time"
 | 
						"time"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	opentelemetry "go.opentelemetry.io/otel"
 | 
						opentelemetry "go.opentelemetry.io/otel"
 | 
				
			||||||
 | 
						"go.opentelemetry.io/otel/attribute"
 | 
				
			||||||
	"go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc"
 | 
						"go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc"
 | 
				
			||||||
	"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
 | 
						"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
 | 
				
			||||||
	"go.opentelemetry.io/otel/exporters/prometheus"
 | 
						"go.opentelemetry.io/otel/exporters/prometheus"
 | 
				
			||||||
@@ -21,7 +23,7 @@ import (
 | 
				
			|||||||
	"go.opentelemetry.io/otel/sdk/metric"
 | 
						"go.opentelemetry.io/otel/sdk/metric"
 | 
				
			||||||
	"go.opentelemetry.io/otel/sdk/resource"
 | 
						"go.opentelemetry.io/otel/sdk/resource"
 | 
				
			||||||
	traceSDK "go.opentelemetry.io/otel/sdk/trace"
 | 
						traceSDK "go.opentelemetry.io/otel/sdk/trace"
 | 
				
			||||||
	semconv "go.opentelemetry.io/otel/semconv/v1.24.0"
 | 
						semconv "go.opentelemetry.io/otel/semconv/v1.27.0"
 | 
				
			||||||
	trace "go.opentelemetry.io/otel/trace"
 | 
						trace "go.opentelemetry.io/otel/trace"
 | 
				
			||||||
	"go.opentelemetry.io/otel/trace/noop"
 | 
						"go.opentelemetry.io/otel/trace/noop"
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
@@ -38,14 +40,20 @@ var (
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
const defMetricInterval = 15 * time.Second
 | 
					const defMetricInterval = 15 * time.Second
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// Init prepares otel, loading a tracer and meter stored in appp context.
 | 
				
			||||||
// Context must carry config.AppConfig
 | 
					// Context must carry config.AppConfig
 | 
				
			||||||
func Init(ctx context.Context) (context.Context, func(context.Context) error) {
 | 
					func Init(ctx context.Context) (context.Context, func(context.Context) error) {
 | 
				
			||||||
	cfg := config.MustFromCtx(ctx)
 | 
						cfg := config.MustFromCtx(ctx)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	// Nothing to do here if not enabled
 | 
						// Nothing to do here if not enabled
 | 
				
			||||||
	if !cfg.OTEL.Enabled {
 | 
						if !cfg.OTELEnabled() {
 | 
				
			||||||
		opentelemetry.SetMeterProvider(noopMetric.NewMeterProvider())
 | 
							opentelemetry.SetMeterProvider(noopMetric.NewMeterProvider())
 | 
				
			||||||
		opentelemetry.SetTracerProvider(noop.NewTracerProvider())
 | 
							opentelemetry.SetTracerProvider(noop.NewTracerProvider())
 | 
				
			||||||
 | 
							// Won't function with noop providers
 | 
				
			||||||
 | 
							meter := opentelemetry.Meter(cfg.Name)
 | 
				
			||||||
 | 
							ctx = AddMeterToCtx(ctx, meter)
 | 
				
			||||||
 | 
							tracer := opentelemetry.Tracer(cfg.Name)
 | 
				
			||||||
 | 
							ctx = AddTracerToCtx(ctx, tracer)
 | 
				
			||||||
		return ctx, func(context.Context) error {
 | 
							return ctx, func(context.Context) error {
 | 
				
			||||||
			return nil
 | 
								return nil
 | 
				
			||||||
		}
 | 
							}
 | 
				
			||||||
@@ -62,12 +70,12 @@ func Init(ctx context.Context) (context.Context, func(context.Context) error) {
 | 
				
			|||||||
	if cfg.OTEL.StdoutEnabled {
 | 
						if cfg.OTEL.StdoutEnabled {
 | 
				
			||||||
		options = append(options, EnableStdoutExporter)
 | 
							options = append(options, EnableStdoutExporter)
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
	if cfg.OTEL.MetricIntervalSecs > 0 {
 | 
					 | 
				
			||||||
		metricInterval = time.Duration(cfg.OTEL.MetricIntervalSecs) * time.Second
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
	if cfg.OTEL.PrometheusEnabled {
 | 
						if cfg.OTEL.PrometheusEnabled {
 | 
				
			||||||
		options = append(options, EnablePrometheusExporter)
 | 
							options = append(options, EnablePrometheusExporter)
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
 | 
						if cfg.OTEL.MetricIntervalSecs > 0 {
 | 
				
			||||||
 | 
							metricInterval = time.Duration(cfg.OTEL.MetricIntervalSecs) * time.Second
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
	options = append(options,
 | 
						options = append(options,
 | 
				
			||||||
		WithMetricExportInterval(metricInterval))
 | 
							WithMetricExportInterval(metricInterval))
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@@ -134,7 +142,7 @@ func newPropagator() propagation.TextMapPropagator {
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
func (s *settings) newTracerProvider(ctx context.Context) (traceProvider *traceSDK.TracerProvider, err error) {
 | 
					func (s *settings) newTracerProvider(ctx context.Context) (traceProvider *traceSDK.TracerProvider, err error) {
 | 
				
			||||||
	traceOpts := []traceSDK.TracerProviderOption{
 | 
						traceOpts := []traceSDK.TracerProviderOption{
 | 
				
			||||||
		traceSDK.WithResource(newResource()),
 | 
							traceSDK.WithResource(newResource(ctx)),
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	host, set := os.LookupEnv("OTEL_EXPORTER_OTLP_ENDPOINT")
 | 
						host, set := os.LookupEnv("OTEL_EXPORTER_OTLP_ENDPOINT")
 | 
				
			||||||
@@ -159,8 +167,16 @@ func (s *settings) newTracerProvider(ctx context.Context) (traceProvider *traceS
 | 
				
			|||||||
	return
 | 
						return
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func newResource() *resource.Resource {
 | 
					func newResource(ctx context.Context) *resource.Resource {
 | 
				
			||||||
	return resource.NewWithAttributes(semconv.SchemaURL)
 | 
						cfg := config.MustFromCtx(ctx)
 | 
				
			||||||
 | 
						attributes := []attribute.KeyValue{
 | 
				
			||||||
 | 
							semconv.ServiceName(cfg.Name),
 | 
				
			||||||
 | 
							semconv.ServiceVersion(cfg.Version),
 | 
				
			||||||
 | 
							semconv.DeploymentEnvironmentName(cfg.Environment),
 | 
				
			||||||
 | 
							semconv.K8SPodName(os.Getenv("HOSTNAME")),
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						return resource.NewWithAttributes(semconv.SchemaURL, attributes...)
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// Configures meter provider
 | 
					// Configures meter provider
 | 
				
			||||||
@@ -187,7 +203,7 @@ func (s *settings) newMeterProvider(ctx context.Context) (*metric.MeterProvider,
 | 
				
			|||||||
	host, set := os.LookupEnv("OTEL_EXPORTER_OTLP_ENDPOINT")
 | 
						host, set := os.LookupEnv("OTEL_EXPORTER_OTLP_ENDPOINT")
 | 
				
			||||||
	var otlpExporter *otlpmetricgrpc.Exporter
 | 
						var otlpExporter *otlpmetricgrpc.Exporter
 | 
				
			||||||
	if set && host != "" {
 | 
						if set && host != "" {
 | 
				
			||||||
		if exp, err := otlpmetricgrpc.New(ctx, otlpmetricgrpc.WithInsecure()); err != nil {
 | 
							if exp, err := otlpmetricgrpc.New(ctx); err != nil {
 | 
				
			||||||
			return nil, fmt.Errorf("otlpmetricgrpc.New: %w", err)
 | 
								return nil, fmt.Errorf("otlpmetricgrpc.New: %w", err)
 | 
				
			||||||
		} else {
 | 
							} else {
 | 
				
			||||||
			otlpExporter = exp
 | 
								otlpExporter = exp
 | 
				
			||||||
@@ -197,6 +213,7 @@ func (s *settings) newMeterProvider(ctx context.Context) (*metric.MeterProvider,
 | 
				
			|||||||
	var meterProvider *metric.MeterProvider
 | 
						var meterProvider *metric.MeterProvider
 | 
				
			||||||
	if otlpExporter != nil {
 | 
						if otlpExporter != nil {
 | 
				
			||||||
		metricOptions = append(metricOptions,
 | 
							metricOptions = append(metricOptions,
 | 
				
			||||||
 | 
								metric.WithResource(newResource(ctx)),
 | 
				
			||||||
			metric.WithReader(exporter),
 | 
								metric.WithReader(exporter),
 | 
				
			||||||
			metric.WithReader(
 | 
								metric.WithReader(
 | 
				
			||||||
				metric.NewPeriodicReader(
 | 
									metric.NewPeriodicReader(
 | 
				
			||||||
@@ -204,12 +221,11 @@ func (s *settings) newMeterProvider(ctx context.Context) (*metric.MeterProvider,
 | 
				
			|||||||
					metric.WithInterval(s.MetricExportInterval),
 | 
										metric.WithInterval(s.MetricExportInterval),
 | 
				
			||||||
				),
 | 
									),
 | 
				
			||||||
			),
 | 
								),
 | 
				
			||||||
			metric.WithResource(newResource()),
 | 
					 | 
				
			||||||
		)
 | 
							)
 | 
				
			||||||
	} else {
 | 
						} else {
 | 
				
			||||||
		metricOptions = append(metricOptions,
 | 
							metricOptions = append(metricOptions,
 | 
				
			||||||
 | 
								metric.WithResource(newResource(ctx)),
 | 
				
			||||||
			metric.WithReader(exporter),
 | 
								metric.WithReader(exporter),
 | 
				
			||||||
			metric.WithResource(newResource()),
 | 
					 | 
				
			||||||
		)
 | 
							)
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@@ -218,7 +234,7 @@ func (s *settings) newMeterProvider(ctx context.Context) (*metric.MeterProvider,
 | 
				
			|||||||
	return meterProvider, nil
 | 
						return meterProvider, nil
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// Creates a new tracer from the global opentelemetry provider
 | 
					// NewTracer creates a new tracer from the global opentelemetry provider
 | 
				
			||||||
func NewTracer(options ...trace.TracerOption) trace.Tracer {
 | 
					func NewTracer(options ...trace.TracerOption) trace.Tracer {
 | 
				
			||||||
	return opentelemetry.GetTracerProvider().Tracer(
 | 
						return opentelemetry.GetTracerProvider().Tracer(
 | 
				
			||||||
		os.Getenv("OTEL_SERVICE_NAME"),
 | 
							os.Getenv("OTEL_SERVICE_NAME"),
 | 
				
			||||||
 
 | 
				
			|||||||
							
								
								
									
										66
									
								
								pkg/otel/otel_test.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										66
									
								
								pkg/otel/otel_test.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,66 @@
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
 | 
					package otel
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"context"
 | 
				
			||||||
 | 
						"testing"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"github.com/stretchr/testify/assert"
 | 
				
			||||||
 | 
						"go.opentelemetry.io/otel/metric/noop"
 | 
				
			||||||
 | 
						"go.opentelemetry.io/otel/trace"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"gitea.libretechconsulting.com/rmcguire/go-app/pkg/config"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func TestInit(t *testing.T) {
 | 
				
			||||||
 | 
						cfg := &config.AppConfig{
 | 
				
			||||||
 | 
							Name: "test-app",
 | 
				
			||||||
 | 
							OTEL: &config.OTELConfig{
 | 
				
			||||||
 | 
								Enabled: true,
 | 
				
			||||||
 | 
							},
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						ctx := cfg.AddToCtx(context.Background())
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						ctx, shutdown := Init(ctx)
 | 
				
			||||||
 | 
						defer shutdown(context.Background())
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						assert.NotNil(t, ctx.Value(ctxKeyTracer))
 | 
				
			||||||
 | 
						assert.NotNil(t, ctx.Value(ctxKeyMeter))
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func TestInit_Disabled(t *testing.T) {
 | 
				
			||||||
 | 
						cfg := &config.AppConfig{
 | 
				
			||||||
 | 
							Name: "test-app",
 | 
				
			||||||
 | 
							OTEL: &config.OTELConfig{
 | 
				
			||||||
 | 
								Enabled: false,
 | 
				
			||||||
 | 
							},
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						ctx := cfg.AddToCtx(context.Background())
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						ctx, shutdown := Init(ctx)
 | 
				
			||||||
 | 
						defer shutdown(context.Background())
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						assert.NotNil(t, ctx.Value(ctxKeyTracer))
 | 
				
			||||||
 | 
						assert.NotNil(t, ctx.Value(ctxKeyMeter))
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func TestContextFuncs(t *testing.T) {
 | 
				
			||||||
 | 
						tracer := trace.NewNoopTracerProvider().Tracer("test")
 | 
				
			||||||
 | 
						meter := noop.NewMeterProvider().Meter("test")
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						ctx := context.Background()
 | 
				
			||||||
 | 
						ctx = AddTracerToCtx(ctx, tracer)
 | 
				
			||||||
 | 
						ctx = AddMeterToCtx(ctx, meter)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						assert.Equal(t, tracer, MustTracerFromCtx(ctx))
 | 
				
			||||||
 | 
						assert.Equal(t, meter, MustMeterFromCtx(ctx))
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func TestContextFuncs_Panic(t *testing.T) {
 | 
				
			||||||
 | 
						assert.Panics(t, func() {
 | 
				
			||||||
 | 
							MustTracerFromCtx(context.Background())
 | 
				
			||||||
 | 
						})
 | 
				
			||||||
 | 
						assert.Panics(t, func() {
 | 
				
			||||||
 | 
							MustMeterFromCtx(context.Background())
 | 
				
			||||||
 | 
						})
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
							
								
								
									
										65
									
								
								pkg/srv/grpc/gateway.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										65
									
								
								pkg/srv/grpc/gateway.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,65 @@
 | 
				
			|||||||
 | 
					package grpc
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"context"
 | 
				
			||||||
 | 
						"errors"
 | 
				
			||||||
 | 
						"fmt"
 | 
				
			||||||
 | 
						"net"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
 | 
				
			||||||
 | 
						"go.opentelemetry.io/otel/attribute"
 | 
				
			||||||
 | 
						"go.opentelemetry.io/otel/codes"
 | 
				
			||||||
 | 
						"go.opentelemetry.io/otel/trace"
 | 
				
			||||||
 | 
						"google.golang.org/grpc"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"gitea.libretechconsulting.com/rmcguire/go-app/pkg/srv/grpc/opts"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (a *appGRPCServer) registerServiceGatewayHandlers(ctx context.Context, service *opts.GRPCService) {
 | 
				
			||||||
 | 
						if len(service.GwRegistrationFuncs) < 1 {
 | 
				
			||||||
 | 
							return
 | 
				
			||||||
 | 
						} else if a.gatewayMux == nil {
 | 
				
			||||||
 | 
							a.gatewayMux = runtime.NewServeMux(a.opts.GRPCGatewayOpts...)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						ctx, span := a.tracer.Start(ctx, "appgrpc.init.prepare.service.gwHandlers", trace.WithAttributes(
 | 
				
			||||||
 | 
							attribute.String("service", service.Name),
 | 
				
			||||||
 | 
							attribute.Int("gwHandlers", len(service.GwRegistrationFuncs)),
 | 
				
			||||||
 | 
						))
 | 
				
			||||||
 | 
						defer span.End()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						clientConn := a.GetClientConn(ctx)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						var errs error
 | 
				
			||||||
 | 
						for _, registerGW := range service.GwRegistrationFuncs {
 | 
				
			||||||
 | 
							errs = errors.Join(errs, registerGW(ctx, a.gatewayMux, clientConn))
 | 
				
			||||||
 | 
							a.logger.Debug().Any("fwo", a.gatewayMux.GetForwardResponseOptions()).
 | 
				
			||||||
 | 
								Msg("calling gateway registration func")
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						if errs != nil {
 | 
				
			||||||
 | 
							panic(errs)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (a *appGRPCServer) GetClientConn(ctx context.Context) *grpc.ClientConn {
 | 
				
			||||||
 | 
						span := trace.SpanFromContext(ctx)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						host, port, err := net.SplitHostPort(a.opts.Listen)
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							panic(err)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						if host == "" || host == "0.0.0.0" {
 | 
				
			||||||
 | 
							host = "localhost"
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						clientConn, err := grpc.NewClient(fmt.Sprintf("%s:%s", host, port), a.opts.GRPCDialOpts...)
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							span.RecordError(err)
 | 
				
			||||||
 | 
							span.SetStatus(codes.Error, err.Error())
 | 
				
			||||||
 | 
							panic(err)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						return clientConn
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
							
								
								
									
										102
									
								
								pkg/srv/grpc/grpc.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										102
									
								
								pkg/srv/grpc/grpc.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,102 @@
 | 
				
			|||||||
 | 
					// Package grpc provides a gRPC server implementation with OpenTelemetry integration
 | 
				
			||||||
 | 
					// and gRPC Gateway for RESTful API exposure.
 | 
				
			||||||
 | 
					package grpc
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"context"
 | 
				
			||||||
 | 
						"strings"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
 | 
				
			||||||
 | 
						"github.com/rs/zerolog"
 | 
				
			||||||
 | 
						"go.opentelemetry.io/otel/attribute"
 | 
				
			||||||
 | 
						"go.opentelemetry.io/otel/codes"
 | 
				
			||||||
 | 
						"go.opentelemetry.io/otel/metric"
 | 
				
			||||||
 | 
						"go.opentelemetry.io/otel/trace"
 | 
				
			||||||
 | 
						"google.golang.org/grpc"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						appotel "gitea.libretechconsulting.com/rmcguire/go-app/pkg/otel"
 | 
				
			||||||
 | 
						"gitea.libretechconsulting.com/rmcguire/go-app/pkg/srv/grpc/opts"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					type appGRPCServer struct {
 | 
				
			||||||
 | 
						ctx          context.Context
 | 
				
			||||||
 | 
						tracer       trace.Tracer
 | 
				
			||||||
 | 
						meter        metric.Meter
 | 
				
			||||||
 | 
						opts         *opts.GRPCOpts
 | 
				
			||||||
 | 
						serverOpts   []grpc.ServerOption
 | 
				
			||||||
 | 
						logger       *zerolog.Logger
 | 
				
			||||||
 | 
						server       *grpc.Server
 | 
				
			||||||
 | 
						gatewayMux   *runtime.ServeMux
 | 
				
			||||||
 | 
						shutdownFunc func(context.Context) error
 | 
				
			||||||
 | 
						doneChan     chan error
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// InitGRPCServer initializes and starts a gRPC server.
 | 
				
			||||||
 | 
					// It returns a shutdown function, a channel to signal completion or error,
 | 
				
			||||||
 | 
					// and an error if the server fails to start.
 | 
				
			||||||
 | 
					func InitGRPCServer(ctx context.Context, opts *opts.GRPCOpts) (
 | 
				
			||||||
 | 
						func(context.Context) error, <-chan error, error,
 | 
				
			||||||
 | 
					) {
 | 
				
			||||||
 | 
						appGRPC := &appGRPCServer{
 | 
				
			||||||
 | 
							ctx:        ctx,
 | 
				
			||||||
 | 
							tracer:     appotel.GetTracer(ctx, "grpc"),
 | 
				
			||||||
 | 
							meter:      appotel.GetMeter(ctx, "grpc"),
 | 
				
			||||||
 | 
							opts:       opts,
 | 
				
			||||||
 | 
							serverOpts: make([]grpc.ServerOption, 0),
 | 
				
			||||||
 | 
							logger:     zerolog.Ctx(ctx),
 | 
				
			||||||
 | 
							doneChan:   make(chan error),
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						ctx, span := appGRPC.tracer.Start(ctx, "appgrpc.init")
 | 
				
			||||||
 | 
						defer span.End()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// Prepare grpc.Server for use
 | 
				
			||||||
 | 
						if err := appGRPC.prepGRPCServer(ctx); err != nil {
 | 
				
			||||||
 | 
							span.RecordError(err)
 | 
				
			||||||
 | 
							span.SetStatus(codes.Error, "failed to prepare GRPC Server")
 | 
				
			||||||
 | 
							return nil, nil, err
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// Load span with server info
 | 
				
			||||||
 | 
						span.SetAttributes(appGRPC.getServerAttributes()...)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						err := appGRPC.runGRPCServer(ctx)
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							span.RecordError(err)
 | 
				
			||||||
 | 
							span.SetStatus(codes.Error, "failed to start GRPC Server")
 | 
				
			||||||
 | 
							return nil, nil, err
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						appGRPC.logger.Debug().Msg("GRPC Server Started")
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						span.SetStatus(codes.Ok, "")
 | 
				
			||||||
 | 
						return appGRPC.shutdownFunc, appGRPC.doneChan, nil
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// Convert grpc.ServiceInfo map to []attribute.KeyValue
 | 
				
			||||||
 | 
					func (a *appGRPCServer) getServerAttributes() []attribute.KeyValue {
 | 
				
			||||||
 | 
						var attrs []attribute.KeyValue
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						for serviceName, info := range a.server.GetServiceInfo() {
 | 
				
			||||||
 | 
							// Add the service name
 | 
				
			||||||
 | 
							attrs = append(attrs, attribute.String("grpc.service", serviceName))
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							// Convert methods into a comma-separated string
 | 
				
			||||||
 | 
							var methods []string
 | 
				
			||||||
 | 
							for _, method := range info.Methods {
 | 
				
			||||||
 | 
								methods = append(methods, method.Name)
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							// Add methods if present
 | 
				
			||||||
 | 
							if len(methods) > 0 {
 | 
				
			||||||
 | 
								attrs = append(attrs, attribute.String("grpc.service.methods", strings.Join(methods, ",")))
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							// If metadata is a string, store it
 | 
				
			||||||
 | 
							if metadata, ok := info.Metadata.(string); ok && metadata != "" {
 | 
				
			||||||
 | 
								attrs = append(attrs, attribute.String("grpc.service.metadata", metadata))
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						return attrs
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
							
								
								
									
										111
									
								
								pkg/srv/grpc/grpc_test.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										111
									
								
								pkg/srv/grpc/grpc_test.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,111 @@
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
 | 
					package grpc
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"context"
 | 
				
			||||||
 | 
						"testing"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"github.com/stretchr/testify/assert"
 | 
				
			||||||
 | 
						"google.golang.org/grpc"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"gitea.libretechconsulting.com/rmcguire/go-app/pkg/config"
 | 
				
			||||||
 | 
						"gitea.libretechconsulting.com/rmcguire/go-app/pkg/otel"
 | 
				
			||||||
 | 
						"gitea.libretechconsulting.com/rmcguire/go-app/pkg/srv/grpc/opts"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// Mock gRPC service
 | 
				
			||||||
 | 
					type mockService struct{}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					type MockServiceServer interface {
 | 
				
			||||||
 | 
						TestMethod(context.Context, *mockRequest) (*mockResponse, error)
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					type mockRequest struct{}
 | 
				
			||||||
 | 
					type mockResponse struct{}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (s *mockService) TestMethod(ctx context.Context, req *mockRequest) (*mockResponse, error) {
 | 
				
			||||||
 | 
						return &mockResponse{}, nil
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					var _MockService_serviceDesc = grpc.ServiceDesc{
 | 
				
			||||||
 | 
						ServiceName: "test.MockService",
 | 
				
			||||||
 | 
						HandlerType: (*MockServiceServer)(nil),
 | 
				
			||||||
 | 
						Methods: []grpc.MethodDesc{
 | 
				
			||||||
 | 
							{
 | 
				
			||||||
 | 
								MethodName: "TestMethod",
 | 
				
			||||||
 | 
								Handler: func(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
 | 
				
			||||||
 | 
									in := new(mockRequest)
 | 
				
			||||||
 | 
									if err := dec(in); err != nil {
 | 
				
			||||||
 | 
										return nil, err
 | 
				
			||||||
 | 
									}
 | 
				
			||||||
 | 
									if interceptor == nil {
 | 
				
			||||||
 | 
										return srv.(MockServiceServer).TestMethod(ctx, in)
 | 
				
			||||||
 | 
									}
 | 
				
			||||||
 | 
									info := &grpc.UnaryServerInfo{
 | 
				
			||||||
 | 
										Server:     srv,
 | 
				
			||||||
 | 
										FullMethod: "/test.MockService/TestMethod",
 | 
				
			||||||
 | 
									}
 | 
				
			||||||
 | 
									handler := func(ctx context.Context, req interface{}) (interface{}, error) {
 | 
				
			||||||
 | 
										return srv.(MockServiceServer).TestMethod(ctx, req.(*mockRequest))
 | 
				
			||||||
 | 
									}
 | 
				
			||||||
 | 
									return interceptor(ctx, in, info, handler)
 | 
				
			||||||
 | 
								},
 | 
				
			||||||
 | 
							},
 | 
				
			||||||
 | 
						},
 | 
				
			||||||
 | 
						Streams:  []grpc.StreamDesc{},
 | 
				
			||||||
 | 
						Metadata: "mock.proto",
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func TestInitGRPCServer(t *testing.T) {
 | 
				
			||||||
 | 
						cfg := &config.AppConfig{
 | 
				
			||||||
 | 
							Name: "test-app",
 | 
				
			||||||
 | 
							GRPC: &config.GRPCConfig{
 | 
				
			||||||
 | 
								Enabled: true,
 | 
				
			||||||
 | 
								Listen:  "127.0.0.1:0", // Use random available port
 | 
				
			||||||
 | 
							},
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						ctx := cfg.AddToCtx(context.Background())
 | 
				
			||||||
 | 
						ctx, _ = otel.Init(ctx)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						grpcOpts := &opts.GRPCOpts{
 | 
				
			||||||
 | 
							GRPCConfig: cfg.GRPC,
 | 
				
			||||||
 | 
							AppGRPC: &opts.AppGRPC{
 | 
				
			||||||
 | 
								Services: []*opts.GRPCService{
 | 
				
			||||||
 | 
									{
 | 
				
			||||||
 | 
										Name:    "mock",
 | 
				
			||||||
 | 
										Type:    &_MockService_serviceDesc,
 | 
				
			||||||
 | 
										Service: &mockService{},
 | 
				
			||||||
 | 
									},
 | 
				
			||||||
 | 
								},
 | 
				
			||||||
 | 
							},
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						shutdown, done, err := InitGRPCServer(ctx, grpcOpts)
 | 
				
			||||||
 | 
						assert.NoError(t, err)
 | 
				
			||||||
 | 
						assert.NotNil(t, shutdown)
 | 
				
			||||||
 | 
						assert.NotNil(t, done)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// Shutdown the server
 | 
				
			||||||
 | 
						err = shutdown(context.Background())
 | 
				
			||||||
 | 
						assert.NoError(t, err)
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func TestInitGRPCServer_NoServices(t *testing.T) {
 | 
				
			||||||
 | 
						cfg := &config.AppConfig{
 | 
				
			||||||
 | 
							Name: "test-app",
 | 
				
			||||||
 | 
							GRPC: &config.GRPCConfig{
 | 
				
			||||||
 | 
								Enabled: true,
 | 
				
			||||||
 | 
								Listen:  "127.0.0.1:0",
 | 
				
			||||||
 | 
							},
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						ctx := cfg.AddToCtx(context.Background())
 | 
				
			||||||
 | 
						ctx, _ = otel.Init(ctx)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						grpcOpts := &opts.GRPCOpts{
 | 
				
			||||||
 | 
							GRPCConfig: cfg.GRPC,
 | 
				
			||||||
 | 
							AppGRPC:    &opts.AppGRPC{},
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						_, _, err := InitGRPCServer(ctx, grpcOpts)
 | 
				
			||||||
 | 
						assert.Error(t, err)
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
							
								
								
									
										51
									
								
								pkg/srv/grpc/logger.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										51
									
								
								pkg/srv/grpc/logger.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,51 @@
 | 
				
			|||||||
 | 
					package grpc
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"context"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						grpclogging "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/logging"
 | 
				
			||||||
 | 
						"github.com/rs/zerolog"
 | 
				
			||||||
 | 
						"github.com/rs/zerolog/log"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// GRPCLogger is a grpc logging middleware compatible logger
 | 
				
			||||||
 | 
					// implementation using a zerolog logger, either from
 | 
				
			||||||
 | 
					// the global logger or a context logger.
 | 
				
			||||||
 | 
					type GRPCLogger struct {
 | 
				
			||||||
 | 
						logger zerolog.Logger
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// NewGRPCLogger returns a grpcLogger using the global zerolog Logger.
 | 
				
			||||||
 | 
					func NewGRPCLogger() *GRPCLogger {
 | 
				
			||||||
 | 
						return &GRPCLogger{logger: log.Logger}
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// NewGRPCContextLogger returns a grpcLogger using the zerolog logger in the provided context.
 | 
				
			||||||
 | 
					func NewGRPCContextLogger(ctx context.Context) *GRPCLogger {
 | 
				
			||||||
 | 
						logger := log.Ctx(ctx)
 | 
				
			||||||
 | 
						return &GRPCLogger{logger: *logger}
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// Log logs the fields for given log level. We can assume users (middleware library) will put fields in pairs and
 | 
				
			||||||
 | 
					// those will be unique.
 | 
				
			||||||
 | 
					func (l *GRPCLogger) Log(ctx context.Context, level grpclogging.Level, msg string, fields ...any) {
 | 
				
			||||||
 | 
						var event *zerolog.Event
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						switch level {
 | 
				
			||||||
 | 
						case grpclogging.LevelDebug:
 | 
				
			||||||
 | 
							event = l.logger.Debug()
 | 
				
			||||||
 | 
						case grpclogging.LevelInfo:
 | 
				
			||||||
 | 
							event = l.logger.Info()
 | 
				
			||||||
 | 
						case grpclogging.LevelWarn:
 | 
				
			||||||
 | 
							event = l.logger.Warn()
 | 
				
			||||||
 | 
						case grpclogging.LevelError:
 | 
				
			||||||
 | 
							event = l.logger.Error()
 | 
				
			||||||
 | 
						default:
 | 
				
			||||||
 | 
							event = l.logger.Warn().
 | 
				
			||||||
 | 
								Int("unknowngrpcloglevel", int(level))
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						event.Ctx(ctx)
 | 
				
			||||||
 | 
						event.Fields(fields)
 | 
				
			||||||
 | 
						event.Msg(msg)
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
							
								
								
									
										43
									
								
								pkg/srv/grpc/opts/config.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										43
									
								
								pkg/srv/grpc/opts/config.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,43 @@
 | 
				
			|||||||
 | 
					package opts
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"context"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
 | 
				
			||||||
 | 
						"google.golang.org/grpc"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"gitea.libretechconsulting.com/rmcguire/go-app/pkg/config"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					type GRPCOpts struct {
 | 
				
			||||||
 | 
						*config.GRPCConfig // Settings configurable by env or yaml
 | 
				
			||||||
 | 
						*AppGRPC           // Settings provided in code
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					type AppGRPC struct {
 | 
				
			||||||
 | 
						Services           []*GRPCService
 | 
				
			||||||
 | 
						UnaryInterceptors  []grpc.UnaryServerInterceptor
 | 
				
			||||||
 | 
						StreamInterceptors []grpc.StreamServerInterceptor
 | 
				
			||||||
 | 
						GRPCOpts           []grpc.ServerOption
 | 
				
			||||||
 | 
						GRPCDialOpts       []grpc.DialOption        // Map ServerOptions to DialOpts for GRPC Gateway support
 | 
				
			||||||
 | 
						GRPCGatewayOpts    []runtime.ServeMuxOption // Configure grpc-gateway ServeMux
 | 
				
			||||||
 | 
						GRPCDone           <-chan error
 | 
				
			||||||
 | 
						gatewayMux         *runtime.ServeMux
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					type GRPCService struct {
 | 
				
			||||||
 | 
						Name                string               // Descriptive name of service
 | 
				
			||||||
 | 
						Type                *grpc.ServiceDesc    // Type (from protoc generated code)
 | 
				
			||||||
 | 
						Service             any                  // Implementation of GRPCService.Type (ptr)
 | 
				
			||||||
 | 
						GwRegistrationFuncs []GwRegistrationFunc // Gateway regustration handler funcs
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					type GwRegistrationFunc func(context.Context, *runtime.ServeMux, *grpc.ClientConn) error
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (a *AppGRPC) SetGatewayMux(mux *runtime.ServeMux) {
 | 
				
			||||||
 | 
						a.gatewayMux = mux
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (a *AppGRPC) GetGatewayMux() *runtime.ServeMux {
 | 
				
			||||||
 | 
						return a.gatewayMux
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
							
								
								
									
										126
									
								
								pkg/srv/grpc/prepare.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										126
									
								
								pkg/srv/grpc/prepare.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,126 @@
 | 
				
			|||||||
 | 
					package grpc
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"context"
 | 
				
			||||||
 | 
						"errors"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"buf.build/go/protovalidate"
 | 
				
			||||||
 | 
						grpclogging "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/logging"
 | 
				
			||||||
 | 
						protovalidate_middleware "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/protovalidate"
 | 
				
			||||||
 | 
						"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
 | 
				
			||||||
 | 
						"go.opentelemetry.io/otel"
 | 
				
			||||||
 | 
						"go.opentelemetry.io/otel/attribute"
 | 
				
			||||||
 | 
						"go.opentelemetry.io/otel/codes"
 | 
				
			||||||
 | 
						"go.opentelemetry.io/otel/trace"
 | 
				
			||||||
 | 
						"google.golang.org/grpc"
 | 
				
			||||||
 | 
						"google.golang.org/grpc/reflection"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (a *appGRPCServer) prepGRPCServer(spanCtx context.Context) error {
 | 
				
			||||||
 | 
						ctx, span := a.tracer.Start(spanCtx, "appgrpc.init.prepare")
 | 
				
			||||||
 | 
						defer span.End()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						if len(a.opts.Services) < 1 {
 | 
				
			||||||
 | 
							err := errors.New("refusing to create grpc server with no services")
 | 
				
			||||||
 | 
							a.logger.Err(err).Send()
 | 
				
			||||||
 | 
							span.RecordError(err)
 | 
				
			||||||
 | 
							span.SetStatus(codes.Error, err.Error())
 | 
				
			||||||
 | 
							return err
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// Prepare GRPC Server Opts
 | 
				
			||||||
 | 
						a.prepareOTEL(ctx)
 | 
				
			||||||
 | 
						a.prepareLogging(ctx)
 | 
				
			||||||
 | 
						a.prepareProtovalidate(ctx)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// Chain interceptors for unary RPCs
 | 
				
			||||||
 | 
						a.serverOpts = append(a.serverOpts,
 | 
				
			||||||
 | 
							grpc.ChainUnaryInterceptor(a.opts.UnaryInterceptors...))
 | 
				
			||||||
 | 
						span.SetAttributes(attribute.Int("grpc.server.unaryinterceptors",
 | 
				
			||||||
 | 
							len(a.opts.UnaryInterceptors)))
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// Chain interceptors for streaming RPCs
 | 
				
			||||||
 | 
						a.serverOpts = append(a.serverOpts,
 | 
				
			||||||
 | 
							grpc.ChainStreamInterceptor(a.opts.StreamInterceptors...))
 | 
				
			||||||
 | 
						span.SetAttributes(attribute.Int("grpc.server.streaminterceptors",
 | 
				
			||||||
 | 
							len(a.opts.StreamInterceptors)))
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// Prepare GRPC Server
 | 
				
			||||||
 | 
						a.server = grpc.NewServer(a.serverOpts...)
 | 
				
			||||||
 | 
						span.SetAttributes(attribute.Int("grpc.server.serveropts", len(a.serverOpts)))
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// Load given services into server registry
 | 
				
			||||||
 | 
						a.registerGRPCServices(ctx)
 | 
				
			||||||
 | 
						span.SetAttributes(attribute.Int("grpc.server.grpcservices", len(a.opts.Services)))
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// If a grpc-gateway mux was created, store it in opts
 | 
				
			||||||
 | 
						// so it can be used by AppHTTP
 | 
				
			||||||
 | 
						if a.gatewayMux != nil {
 | 
				
			||||||
 | 
							a.opts.SetGatewayMux(a.gatewayMux)
 | 
				
			||||||
 | 
							span.SetAttributes(attribute.Bool("grpc.server.grpcgateway.enabled", true))
 | 
				
			||||||
 | 
						} else {
 | 
				
			||||||
 | 
							span.SetAttributes(attribute.Bool("grpc.server.grpcgateway.enabled", false))
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// Enable reflection if desired
 | 
				
			||||||
 | 
						if a.opts.EnableReflection {
 | 
				
			||||||
 | 
							reflection.Register(a.server)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						span.SetAttributes(attribute.Bool("grpc.server.reflection", a.opts.EnableReflection))
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						span.SetStatus(codes.Ok, "")
 | 
				
			||||||
 | 
						return nil
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// prepareProtovalidate() adds interceptors for buf.build protovalidate
 | 
				
			||||||
 | 
					func (a *appGRPCServer) prepareProtovalidate(spanCtx context.Context) {
 | 
				
			||||||
 | 
						_, span := a.tracer.Start(spanCtx, "appgrpc.init.prepare.protovalidate", trace.WithAttributes(
 | 
				
			||||||
 | 
							attribute.Bool("grpc.server.protovalidate", a.opts.EnableProtovalidate)))
 | 
				
			||||||
 | 
						defer span.End()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						if !a.opts.EnableProtovalidate {
 | 
				
			||||||
 | 
							return
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						validator, err := protovalidate.New()
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							span.RecordError(err)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						a.opts.UnaryInterceptors = append(a.opts.UnaryInterceptors,
 | 
				
			||||||
 | 
							protovalidate_middleware.UnaryServerInterceptor(validator))
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						a.opts.StreamInterceptors = append(a.opts.StreamInterceptors,
 | 
				
			||||||
 | 
							protovalidate_middleware.StreamServerInterceptor(validator))
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (a *appGRPCServer) prepareOTEL(spanCtx context.Context) {
 | 
				
			||||||
 | 
						_, span := a.tracer.Start(spanCtx, "appgrpc.init.prepare.otel", trace.WithAttributes(
 | 
				
			||||||
 | 
							attribute.Bool("grpc.server.instrumented", a.opts.EnableInstrumentation)))
 | 
				
			||||||
 | 
						defer span.End()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						if a.opts.EnableInstrumentation {
 | 
				
			||||||
 | 
							a.serverOpts = append(a.serverOpts,
 | 
				
			||||||
 | 
								grpc.StatsHandler(
 | 
				
			||||||
 | 
									otelgrpc.NewServerHandler(
 | 
				
			||||||
 | 
										otelgrpc.WithTracerProvider(otel.GetTracerProvider()),
 | 
				
			||||||
 | 
										otelgrpc.WithMeterProvider(otel.GetMeterProvider()),
 | 
				
			||||||
 | 
									)))
 | 
				
			||||||
 | 
							span.SetStatus(codes.Ok, "")
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (a *appGRPCServer) prepareLogging(spanCtx context.Context) {
 | 
				
			||||||
 | 
						_, span := a.tracer.Start(spanCtx, "appgrpc.init.prepare.logging", trace.WithAttributes(
 | 
				
			||||||
 | 
							attribute.Bool("grpc.server.instrumentated", a.opts.LogRequests),
 | 
				
			||||||
 | 
							attribute.String("grpc.server.loglevel", a.logger.GetLevel().String())))
 | 
				
			||||||
 | 
						defer span.End()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						if a.opts.LogRequests {
 | 
				
			||||||
 | 
							a.opts.UnaryInterceptors = append(a.opts.UnaryInterceptors,
 | 
				
			||||||
 | 
								grpclogging.UnaryServerInterceptor(NewGRPCContextLogger(a.ctx)))
 | 
				
			||||||
 | 
							a.opts.StreamInterceptors = append(a.opts.StreamInterceptors,
 | 
				
			||||||
 | 
								grpclogging.StreamServerInterceptor(NewGRPCContextLogger(a.ctx)))
 | 
				
			||||||
 | 
							span.SetStatus(codes.Ok, "")
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
							
								
								
									
										66
									
								
								pkg/srv/grpc/run.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										66
									
								
								pkg/srv/grpc/run.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,66 @@
 | 
				
			|||||||
 | 
					package grpc
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"context"
 | 
				
			||||||
 | 
						"net"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"go.opentelemetry.io/otel/codes"
 | 
				
			||||||
 | 
						semconv "go.opentelemetry.io/otel/semconv/v1.27.0"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (a *appGRPCServer) runGRPCServer(spanCtx context.Context) error {
 | 
				
			||||||
 | 
						_, span := a.tracer.Start(spanCtx, "appgrpc.init.start")
 | 
				
			||||||
 | 
						defer span.End()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						span.SetAttributes(
 | 
				
			||||||
 | 
							semconv.RPCSystemGRPC,
 | 
				
			||||||
 | 
							semconv.NetworkProtocolName("grpc"),
 | 
				
			||||||
 | 
							semconv.ServerAddress(a.opts.Listen),
 | 
				
			||||||
 | 
						)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						a.shutdownFunc = a.getShutdownFunc()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						l, err := net.Listen("tcp", a.opts.Listen)
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							a.logger.Err(err).Send()
 | 
				
			||||||
 | 
							span.RecordError(err)
 | 
				
			||||||
 | 
							span.SetStatus(codes.Error, "failed to acquire net listener")
 | 
				
			||||||
 | 
							return err
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						span.AddEvent("network listener acquired")
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// Launch GRPC Server
 | 
				
			||||||
 | 
						go func() {
 | 
				
			||||||
 | 
							if err := a.server.Serve(l); err != nil {
 | 
				
			||||||
 | 
								a.logger.Err(err).Send()
 | 
				
			||||||
 | 
								a.doneChan <- err
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
						}()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						span.AddEvent("grpc server goroutine launched")
 | 
				
			||||||
 | 
						span.SetStatus(codes.Ok, "")
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						return nil
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (a *appGRPCServer) getShutdownFunc() func(context.Context) error {
 | 
				
			||||||
 | 
						return func(ctx context.Context) error {
 | 
				
			||||||
 | 
							stoppedChan := make(chan any)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							go func() {
 | 
				
			||||||
 | 
								a.server.GracefulStop()
 | 
				
			||||||
 | 
								stoppedChan <- nil
 | 
				
			||||||
 | 
							}()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							select {
 | 
				
			||||||
 | 
							case <-stoppedChan:
 | 
				
			||||||
 | 
								a.logger.Warn().Msg("GRPC server shut down gracefully")
 | 
				
			||||||
 | 
								return nil
 | 
				
			||||||
 | 
							case <-ctx.Done():
 | 
				
			||||||
 | 
								a.logger.Warn().Msg("GRPC server shut down hard")
 | 
				
			||||||
 | 
								a.server.Stop()
 | 
				
			||||||
 | 
								return ctx.Err()
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
							
								
								
									
										35
									
								
								pkg/srv/grpc/services.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										35
									
								
								pkg/srv/grpc/services.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,35 @@
 | 
				
			|||||||
 | 
					package grpc
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"context"
 | 
				
			||||||
 | 
						"fmt"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"go.opentelemetry.io/otel/attribute"
 | 
				
			||||||
 | 
						"go.opentelemetry.io/otel/codes"
 | 
				
			||||||
 | 
						"go.opentelemetry.io/otel/trace"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"gitea.libretechconsulting.com/rmcguire/go-app/pkg/srv/grpc/opts"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (a *appGRPCServer) registerGRPCServices(ctx context.Context) {
 | 
				
			||||||
 | 
						ctx, span := a.tracer.Start(ctx, "appgrpc.init.prepare.services", trace.WithAttributes(
 | 
				
			||||||
 | 
							attribute.Int("numServices", len(a.opts.Services)),
 | 
				
			||||||
 | 
						))
 | 
				
			||||||
 | 
						defer span.End()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						for _, service := range a.opts.Services {
 | 
				
			||||||
 | 
							a.registerGRPCService(ctx, service)
 | 
				
			||||||
 | 
							if a.opts.EnableGRPCGateway {
 | 
				
			||||||
 | 
								a.registerServiceGatewayHandlers(ctx, service)
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						span.SetStatus(codes.Ok, "")
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (a *appGRPCServer) registerGRPCService(ctx context.Context, service *opts.GRPCService) {
 | 
				
			||||||
 | 
						span := trace.SpanFromContext(ctx)
 | 
				
			||||||
 | 
						span.AddEvent(fmt.Sprintf("registered %s service", service.Name))
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						a.server.RegisterService(service.Type, service.Service)
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
							
								
								
									
										153
									
								
								pkg/srv/http.go
									
									
									
									
									
								
							
							
						
						
									
										153
									
								
								pkg/srv/http.go
									
									
									
									
									
								
							@@ -1,153 +0,0 @@
 | 
				
			|||||||
package srv
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
import (
 | 
					 | 
				
			||||||
	"context"
 | 
					 | 
				
			||||||
	"net"
 | 
					 | 
				
			||||||
	"net/http"
 | 
					 | 
				
			||||||
	"time"
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	"github.com/prometheus/client_golang/prometheus/promhttp"
 | 
					 | 
				
			||||||
	"github.com/rs/zerolog"
 | 
					 | 
				
			||||||
	"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
 | 
					 | 
				
			||||||
	"go.opentelemetry.io/otel/metric"
 | 
					 | 
				
			||||||
	"go.opentelemetry.io/otel/trace"
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	"gitea.libretechconsulting.com/rmcguire/go-app/pkg/config"
 | 
					 | 
				
			||||||
	"gitea.libretechconsulting.com/rmcguire/go-app/pkg/otel"
 | 
					 | 
				
			||||||
)
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
var (
 | 
					 | 
				
			||||||
	httpMeter       metric.Meter
 | 
					 | 
				
			||||||
	httpTracer      trace.Tracer
 | 
					 | 
				
			||||||
	defReadTimeout  = 10 * time.Second
 | 
					 | 
				
			||||||
	defWriteTimeout = 10 * time.Second
 | 
					 | 
				
			||||||
	defIdleTimeout  = 15 * time.Second
 | 
					 | 
				
			||||||
)
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
type HTTPFunc struct {
 | 
					 | 
				
			||||||
	Path        string
 | 
					 | 
				
			||||||
	HandlerFunc http.HandlerFunc
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
func prepHTTPServer(ctx context.Context, handleFuncs []HTTPFunc, hcFuncs ...HealthCheckFunc) *http.Server {
 | 
					 | 
				
			||||||
	var (
 | 
					 | 
				
			||||||
		cfg = config.MustFromCtx(ctx)
 | 
					 | 
				
			||||||
		l   = zerolog.Ctx(ctx)
 | 
					 | 
				
			||||||
		mux = &http.ServeMux{}
 | 
					 | 
				
			||||||
	)
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	// NOTE: Wraps handle func with otelhttp handler and
 | 
					 | 
				
			||||||
	// inserts route tag
 | 
					 | 
				
			||||||
	otelHandleFunc := func(pattern string, handlerFunc func(http.ResponseWriter, *http.Request)) {
 | 
					 | 
				
			||||||
		handler := otelhttp.WithRouteTag(pattern, http.HandlerFunc(handlerFunc))
 | 
					 | 
				
			||||||
		mux.Handle(pattern, handler) // Associate pattern with handler
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	healthChecks := handleHealthCheckFunc(ctx, hcFuncs...)
 | 
					 | 
				
			||||||
	otelHandleFunc("/health", healthChecks)
 | 
					 | 
				
			||||||
	otelHandleFunc("/", healthChecks)
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	for _, f := range handleFuncs {
 | 
					 | 
				
			||||||
		otelHandleFunc(f.Path, f.HandlerFunc)
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	// Prometheus metrics endpoint
 | 
					 | 
				
			||||||
	if cfg.OTEL.PrometheusEnabled {
 | 
					 | 
				
			||||||
		mux.Handle(cfg.OTEL.PrometheusPath, promhttp.Handler())
 | 
					 | 
				
			||||||
		l.Info().Str("prometheusPath", cfg.OTEL.PrometheusPath).
 | 
					 | 
				
			||||||
			Msg("mounted prometheus metrics endpoint")
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	// Add OTEL, skip health-check spans
 | 
					 | 
				
			||||||
	// NOTE: Add any other span exclusions here
 | 
					 | 
				
			||||||
	handler := otelhttp.NewHandler(mux, "/",
 | 
					 | 
				
			||||||
		otelhttp.WithFilter(func(r *http.Request) bool {
 | 
					 | 
				
			||||||
			switch r.URL.Path {
 | 
					 | 
				
			||||||
			case "/health":
 | 
					 | 
				
			||||||
				return false
 | 
					 | 
				
			||||||
			case cfg.OTEL.PrometheusPath:
 | 
					 | 
				
			||||||
				return false
 | 
					 | 
				
			||||||
			default:
 | 
					 | 
				
			||||||
				return true
 | 
					 | 
				
			||||||
			}
 | 
					 | 
				
			||||||
		}))
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	// Set timeouts from defaults, override
 | 
					 | 
				
			||||||
	// with config timeouts if set
 | 
					 | 
				
			||||||
	readTimeout := defReadTimeout
 | 
					 | 
				
			||||||
	writeTimeout := defWriteTimeout
 | 
					 | 
				
			||||||
	idleTimeout := defIdleTimeout
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	rT, wT, iT := cfg.HTTP.Timeouts()
 | 
					 | 
				
			||||||
	if rT != nil {
 | 
					 | 
				
			||||||
		readTimeout = *rT
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
	if wT != nil {
 | 
					 | 
				
			||||||
		writeTimeout = *wT
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
	if iT != nil {
 | 
					 | 
				
			||||||
		idleTimeout = *iT
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	// Inject logging middleware
 | 
					 | 
				
			||||||
	if cfg.HTTP.LogRequests {
 | 
					 | 
				
			||||||
		handler = loggingMiddleware(ctx, handler)
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	return &http.Server{
 | 
					 | 
				
			||||||
		Addr:         cfg.HTTP.Listen,
 | 
					 | 
				
			||||||
		ReadTimeout:  readTimeout,
 | 
					 | 
				
			||||||
		WriteTimeout: writeTimeout,
 | 
					 | 
				
			||||||
		IdleTimeout:  idleTimeout,
 | 
					 | 
				
			||||||
		Handler:      handler,
 | 
					 | 
				
			||||||
		BaseContext: func(_ net.Listener) context.Context {
 | 
					 | 
				
			||||||
			return ctx
 | 
					 | 
				
			||||||
		},
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
// Returns a shutdown func and a done channel if the
 | 
					 | 
				
			||||||
// server aborts abnormally. Panics on error.
 | 
					 | 
				
			||||||
func MustInitHTTPServer(ctx context.Context, funcs []HTTPFunc, hcFuncs ...HealthCheckFunc) (
 | 
					 | 
				
			||||||
	func(context.Context) error, <-chan interface{},
 | 
					 | 
				
			||||||
) {
 | 
					 | 
				
			||||||
	shutdownFunc, doneChan, err := InitHTTPServer(ctx, funcs, hcFuncs...)
 | 
					 | 
				
			||||||
	if err != nil {
 | 
					 | 
				
			||||||
		panic(err)
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
	return shutdownFunc, doneChan
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
// Returns a shutdown func and a done channel if the
 | 
					 | 
				
			||||||
// server aborts abnormally. Returns error on failure to start
 | 
					 | 
				
			||||||
func InitHTTPServer(ctx context.Context, funcs []HTTPFunc, hcFuncs ...HealthCheckFunc) (
 | 
					 | 
				
			||||||
	func(context.Context) error, <-chan interface{}, error,
 | 
					 | 
				
			||||||
) {
 | 
					 | 
				
			||||||
	l := zerolog.Ctx(ctx)
 | 
					 | 
				
			||||||
	doneChan := make(chan interface{})
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	var server *http.Server
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	httpMeter = otel.GetMeter(ctx, "http")
 | 
					 | 
				
			||||||
	httpTracer = otel.GetTracer(ctx, "http")
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	server = prepHTTPServer(ctx, funcs, hcFuncs...)
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	go func() {
 | 
					 | 
				
			||||||
		l.Debug().Msg("HTTP Server Started")
 | 
					 | 
				
			||||||
		err := server.ListenAndServe()
 | 
					 | 
				
			||||||
		if err != nil && err != http.ErrServerClosed {
 | 
					 | 
				
			||||||
			l.Err(err).Msg("HTTP server error")
 | 
					 | 
				
			||||||
		} else {
 | 
					 | 
				
			||||||
			l.Info().Msg("HTTP server shut down")
 | 
					 | 
				
			||||||
		}
 | 
					 | 
				
			||||||
		doneChan <- nil
 | 
					 | 
				
			||||||
	}()
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	// Shut down http server with a deadline
 | 
					 | 
				
			||||||
	return func(shutdownCtx context.Context) error {
 | 
					 | 
				
			||||||
		l.Debug().Msg("stopping http server")
 | 
					 | 
				
			||||||
		server.Shutdown(shutdownCtx)
 | 
					 | 
				
			||||||
		return nil
 | 
					 | 
				
			||||||
	}, doneChan, nil
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
							
								
								
									
										188
									
								
								pkg/srv/http/http.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										188
									
								
								pkg/srv/http/http.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,188 @@
 | 
				
			|||||||
 | 
					// Package http provides functionality for setting up and managing HTTP servers.
 | 
				
			||||||
 | 
					// It includes features for health checks, Prometheus metrics, OpenTelemetry
 | 
				
			||||||
 | 
					// tracing, and custom middleware integration.
 | 
				
			||||||
 | 
					package http
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"context"
 | 
				
			||||||
 | 
						"fmt"
 | 
				
			||||||
 | 
						"log"
 | 
				
			||||||
 | 
						"net"
 | 
				
			||||||
 | 
						"net/http"
 | 
				
			||||||
 | 
						"os"
 | 
				
			||||||
 | 
						"regexp"
 | 
				
			||||||
 | 
						"strings"
 | 
				
			||||||
 | 
						"time"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"github.com/prometheus/client_golang/prometheus/promhttp"
 | 
				
			||||||
 | 
						"github.com/rs/zerolog"
 | 
				
			||||||
 | 
						"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
 | 
				
			||||||
 | 
						"go.opentelemetry.io/otel/metric"
 | 
				
			||||||
 | 
						"go.opentelemetry.io/otel/trace"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"gitea.libretechconsulting.com/rmcguire/go-app/pkg/config"
 | 
				
			||||||
 | 
						"gitea.libretechconsulting.com/rmcguire/go-app/pkg/otel"
 | 
				
			||||||
 | 
						"gitea.libretechconsulting.com/rmcguire/go-app/pkg/srv/http/opts"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					var (
 | 
				
			||||||
 | 
						httpMeter                   metric.Meter
 | 
				
			||||||
 | 
						httpTracer                  trace.Tracer
 | 
				
			||||||
 | 
						httpPatternWithMethodRegexp = regexp.MustCompile(`(\w+) .*`)
 | 
				
			||||||
 | 
						defReadTimeout              = 10 * time.Second
 | 
				
			||||||
 | 
						defWriteTimeout             = 10 * time.Second
 | 
				
			||||||
 | 
						defIdleTimeout              = 15 * time.Second
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func prepHTTPServer(opts *opts.AppHTTP) *http.Server {
 | 
				
			||||||
 | 
						var (
 | 
				
			||||||
 | 
							cfg = config.MustFromCtx(opts.Ctx)
 | 
				
			||||||
 | 
							l   = zerolog.Ctx(opts.Ctx)
 | 
				
			||||||
 | 
							mux = &http.ServeMux{}
 | 
				
			||||||
 | 
						)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						healthChecks := handleHealthCheckFunc(opts.Ctx, opts.HealthChecks...)
 | 
				
			||||||
 | 
						mux.HandleFunc("/health", healthChecks)
 | 
				
			||||||
 | 
						mux.HandleFunc("/", healthChecks)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						for _, f := range opts.Funcs {
 | 
				
			||||||
 | 
							mux.HandleFunc(f.Path, f.HandlerFunc)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// Prometheus metrics endpoint
 | 
				
			||||||
 | 
						if cfg.OTEL.PrometheusEnabled {
 | 
				
			||||||
 | 
							mux.Handle(cfg.OTEL.PrometheusPath, promhttp.Handler())
 | 
				
			||||||
 | 
							l.Info().Str("prometheusPath", cfg.OTEL.PrometheusPath).
 | 
				
			||||||
 | 
								Msg("mounted prometheus metrics endpoint")
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// Inject extra handlers if given
 | 
				
			||||||
 | 
						// Used for grpc-gateway runtime.ServeMux handlers
 | 
				
			||||||
 | 
						for _, h := range opts.Handlers {
 | 
				
			||||||
 | 
							// prefix must end in / to route sub-paths
 | 
				
			||||||
 | 
							if !strings.HasSuffix(h.Prefix, "/") {
 | 
				
			||||||
 | 
								h.Prefix = h.Prefix + "/"
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							// if enabled, the path prefix is stripped before
 | 
				
			||||||
 | 
							// requests are sent to the handler
 | 
				
			||||||
 | 
							if h.StripPrefix {
 | 
				
			||||||
 | 
								h.Handler = http.StripPrefix(h.Prefix[:len(h.Prefix)-1], h.Handler)
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
							mux.Handle(h.Prefix, otelhttp.WithRouteTag(h.Prefix, h.Handler))
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// Add OTEL instrumentation, filter noise, set span names
 | 
				
			||||||
 | 
						handler := otelhttp.NewHandler(mux, "/",
 | 
				
			||||||
 | 
							// TODO: Make configurable similar to config.http.LogExcludePathRegexps
 | 
				
			||||||
 | 
							otelhttp.WithFilter(func(r *http.Request) bool {
 | 
				
			||||||
 | 
								switch r.URL.Path {
 | 
				
			||||||
 | 
								case "/health":
 | 
				
			||||||
 | 
									return false
 | 
				
			||||||
 | 
								case cfg.OTEL.PrometheusPath:
 | 
				
			||||||
 | 
									return false
 | 
				
			||||||
 | 
								default:
 | 
				
			||||||
 | 
									return true
 | 
				
			||||||
 | 
								}
 | 
				
			||||||
 | 
							}),
 | 
				
			||||||
 | 
							otelhttp.WithSpanNameFormatter(func(operation string, r *http.Request) string {
 | 
				
			||||||
 | 
								endpoint := r.URL.Path
 | 
				
			||||||
 | 
								if _, pattern := mux.Handler(r); pattern != "" {
 | 
				
			||||||
 | 
									endpoint = pattern
 | 
				
			||||||
 | 
								}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
								if httpPatternWithMethodRegexp.MatchString(endpoint) {
 | 
				
			||||||
 | 
									return endpoint
 | 
				
			||||||
 | 
								}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
								return fmt.Sprintf("%s %s", r.Method, endpoint)
 | 
				
			||||||
 | 
							}))
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// Set timeouts from defaults, override
 | 
				
			||||||
 | 
						// with config timeouts if set
 | 
				
			||||||
 | 
						readTimeout := defReadTimeout
 | 
				
			||||||
 | 
						writeTimeout := defWriteTimeout
 | 
				
			||||||
 | 
						idleTimeout := defIdleTimeout
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						rT, wT, iT := cfg.HTTP.Timeouts()
 | 
				
			||||||
 | 
						if rT != nil {
 | 
				
			||||||
 | 
							readTimeout = *rT
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						if wT != nil {
 | 
				
			||||||
 | 
							writeTimeout = *wT
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						if iT != nil {
 | 
				
			||||||
 | 
							idleTimeout = *iT
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// Inject any supplied middleware
 | 
				
			||||||
 | 
						for i := len(opts.Middleware) - 1; i >= 0; i-- {
 | 
				
			||||||
 | 
							mw := opts.Middleware[i]
 | 
				
			||||||
 | 
							next := handler
 | 
				
			||||||
 | 
							handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 | 
				
			||||||
 | 
								mw.ServeHTTP(w, r)
 | 
				
			||||||
 | 
								next.ServeHTTP(w, r)
 | 
				
			||||||
 | 
							})
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// Inject logging middleware
 | 
				
			||||||
 | 
						if cfg.HTTP.LogRequests {
 | 
				
			||||||
 | 
							handler = loggingMiddleware(opts.Ctx, handler)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						return &http.Server{
 | 
				
			||||||
 | 
							Addr:         cfg.HTTP.Listen,
 | 
				
			||||||
 | 
							ReadTimeout:  readTimeout,
 | 
				
			||||||
 | 
							WriteTimeout: writeTimeout,
 | 
				
			||||||
 | 
							IdleTimeout:  idleTimeout,
 | 
				
			||||||
 | 
							Handler:      handler,
 | 
				
			||||||
 | 
							ErrorLog:     log.New(os.Stderr, fmt.Sprintf("Go-HTTP[%s]", cfg.Name), log.Flags()),
 | 
				
			||||||
 | 
							BaseContext: func(_ net.Listener) context.Context {
 | 
				
			||||||
 | 
								return opts.Ctx
 | 
				
			||||||
 | 
							},
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// InitHTTPServer returns a shutdown func and a done channel if the
 | 
				
			||||||
 | 
					// server aborts abnormally. Returns error on failure to start.
 | 
				
			||||||
 | 
					func InitHTTPServer(opts *opts.AppHTTP) (
 | 
				
			||||||
 | 
						func(context.Context) error, <-chan any, error,
 | 
				
			||||||
 | 
					) {
 | 
				
			||||||
 | 
						l := zerolog.Ctx(opts.Ctx)
 | 
				
			||||||
 | 
						doneChan := make(chan any)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						var server *http.Server
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						httpMeter = otel.GetMeter(opts.Ctx, "http")
 | 
				
			||||||
 | 
						httpTracer = otel.GetTracer(opts.Ctx, "http")
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						server = prepHTTPServer(opts)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						go func() {
 | 
				
			||||||
 | 
							var err error
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							if opts.CustomListener != nil {
 | 
				
			||||||
 | 
								err = server.Serve(opts.CustomListener)
 | 
				
			||||||
 | 
							} else {
 | 
				
			||||||
 | 
								err = server.ListenAndServe()
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							if err != nil && err != http.ErrServerClosed {
 | 
				
			||||||
 | 
								l.Err(err).Msg("HTTP server error")
 | 
				
			||||||
 | 
							} else {
 | 
				
			||||||
 | 
								l.Info().Msg("HTTP server shut down")
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							// Notify app initiator
 | 
				
			||||||
 | 
							doneChan <- nil
 | 
				
			||||||
 | 
						}()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						l.Debug().Msg("HTTP Server Started")
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// Shut down http server with a deadline
 | 
				
			||||||
 | 
						return func(shutdownCtx context.Context) error {
 | 
				
			||||||
 | 
							l.Debug().Msg("stopping http server")
 | 
				
			||||||
 | 
							server.Shutdown(shutdownCtx)
 | 
				
			||||||
 | 
							return nil
 | 
				
			||||||
 | 
						}, doneChan, nil
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
@@ -1,4 +1,4 @@
 | 
				
			|||||||
package srv
 | 
					package http
 | 
				
			||||||
 | 
					
 | 
				
			||||||
import (
 | 
					import (
 | 
				
			||||||
	"context"
 | 
						"context"
 | 
				
			||||||
@@ -9,11 +9,11 @@ import (
 | 
				
			|||||||
	"time"
 | 
						"time"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	"github.com/rs/zerolog"
 | 
						"github.com/rs/zerolog"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"gitea.libretechconsulting.com/rmcguire/go-app/pkg/srv/http/opts"
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
type HealthCheckFunc func(context.Context) error
 | 
					func handleHealthCheckFunc(ctx context.Context, hcFuncs ...opts.HealthCheckFunc) func(w http.ResponseWriter, r *http.Request) {
 | 
				
			||||||
 | 
					 | 
				
			||||||
func handleHealthCheckFunc(ctx context.Context, hcFuncs ...HealthCheckFunc) func(w http.ResponseWriter, r *http.Request) {
 | 
					 | 
				
			||||||
	// Return http handle func
 | 
						// Return http handle func
 | 
				
			||||||
	return func(w http.ResponseWriter, r *http.Request) {
 | 
						return func(w http.ResponseWriter, r *http.Request) {
 | 
				
			||||||
		var (
 | 
							var (
 | 
				
			||||||
@@ -55,7 +55,7 @@ func handleHealthCheckFunc(ctx context.Context, hcFuncs ...HealthCheckFunc) func
 | 
				
			|||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func dummyHealthCheck(ctx context.Context) error {
 | 
					func dummyHealthCheck(ctx context.Context) error {
 | 
				
			||||||
	workFor := rand.Intn(750)
 | 
						workFor := rand.Intn(740) + 10 // ensure positive
 | 
				
			||||||
	ticker := time.NewTicker(time.Duration(time.Duration(workFor) * time.Millisecond))
 | 
						ticker := time.NewTicker(time.Duration(time.Duration(workFor) * time.Millisecond))
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	select {
 | 
						select {
 | 
				
			||||||
@@ -1,14 +1,17 @@
 | 
				
			|||||||
package srv
 | 
					package http
 | 
				
			||||||
 | 
					
 | 
				
			||||||
import (
 | 
					import (
 | 
				
			||||||
	"bytes"
 | 
						"bytes"
 | 
				
			||||||
	"context"
 | 
						"context"
 | 
				
			||||||
	"errors"
 | 
						"fmt"
 | 
				
			||||||
 | 
						"io"
 | 
				
			||||||
	"net/http"
 | 
						"net/http"
 | 
				
			||||||
	"regexp"
 | 
						"regexp"
 | 
				
			||||||
	"time"
 | 
						"time"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	"github.com/rs/zerolog"
 | 
						"github.com/rs/zerolog"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"gitea.libretechconsulting.com/rmcguire/go-app/pkg/config"
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
var ExcludeFromLogging = regexp.MustCompile(`\/(ready|live|metrics)$`)
 | 
					var ExcludeFromLogging = regexp.MustCompile(`\/(ready|live|metrics)$`)
 | 
				
			||||||
@@ -20,12 +23,22 @@ type LoggingResponseWriter struct {
 | 
				
			|||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func loggingMiddleware(appCtx context.Context, next http.Handler) http.Handler {
 | 
					func loggingMiddleware(appCtx context.Context, next http.Handler) http.Handler {
 | 
				
			||||||
 | 
						appConfig := config.MustFromCtx(appCtx)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 | 
						return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 | 
				
			||||||
		if ExcludeFromLogging.Match([]byte(r.URL.Path)) {
 | 
							if ExcludeFromLogging.Match([]byte(r.URL.Path)) {
 | 
				
			||||||
			next.ServeHTTP(w, r)
 | 
								next.ServeHTTP(w, r)
 | 
				
			||||||
			return
 | 
								return
 | 
				
			||||||
		}
 | 
							}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							// User-configurable logging exclusions
 | 
				
			||||||
 | 
							for _, re := range appConfig.HTTP.GetExcludeRegexps() {
 | 
				
			||||||
 | 
								if re.MatchString(r.URL.Path) {
 | 
				
			||||||
 | 
									next.ServeHTTP(w, r)
 | 
				
			||||||
 | 
									return
 | 
				
			||||||
 | 
								}
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		log := zerolog.Ctx(appCtx)
 | 
							log := zerolog.Ctx(appCtx)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		start := time.Now()
 | 
							start := time.Now()
 | 
				
			||||||
@@ -41,29 +54,42 @@ func loggingMiddleware(appCtx context.Context, next http.Handler) http.Handler {
 | 
				
			|||||||
			Dur("duration", time.Since(start)).
 | 
								Dur("duration", time.Since(start)).
 | 
				
			||||||
			Msg("http request served")
 | 
								Msg("http request served")
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		// Log response body
 | 
								// Log response with body if not 204
 | 
				
			||||||
 | 
							if lrr.statusCode == http.StatusNoContent {
 | 
				
			||||||
 | 
								trcLog := log.Trace().
 | 
				
			||||||
 | 
									Str("path", r.URL.Path).
 | 
				
			||||||
 | 
									Int("statusCode", lrr.statusCode)
 | 
				
			||||||
 | 
								trcLog.Msg("http response (no content)") // Explicitly log 204
 | 
				
			||||||
 | 
								return                                   // No body to log for 204 No Content
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		trcLog := log.Trace().
 | 
							trcLog := log.Trace().
 | 
				
			||||||
			Str("path", r.URL.Path).
 | 
								Str("path", r.URL.Path).
 | 
				
			||||||
			Int("statusCode", lrr.statusCode)
 | 
								Int("statusCode", lrr.statusCode)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		// Check if it's JSON
 | 
					 | 
				
			||||||
		firstByte, err := lrr.body.ReadByte()
 | 
							firstByte, err := lrr.body.ReadByte()
 | 
				
			||||||
		if err != nil {
 | 
							if err != nil {
 | 
				
			||||||
			trcLog.Err(errors.New("invalid response body")).Send()
 | 
								if err == io.EOF {
 | 
				
			||||||
			return
 | 
									// Body is empty, which might be valid for some non-204 responses.
 | 
				
			||||||
 | 
									trcLog.Msg("http response (empty body)")
 | 
				
			||||||
 | 
								} else {
 | 
				
			||||||
 | 
									// Other error reading the body. Wrap the original error for context.
 | 
				
			||||||
 | 
									trcLog.Err(fmt.Errorf("error reading response body: %w", err)).Send()
 | 
				
			||||||
			}
 | 
								}
 | 
				
			||||||
		lrr.body.UnreadByte()
 | 
								return // No further body processing if there was an error or it was empty
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
							lrr.body.UnreadByte() // Put the byte back for Bytes() to read
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		if firstByte == '{' {
 | 
							if firstByte == '{' {
 | 
				
			||||||
			trcLog = trcLog.RawJSON("response", lrr.body.Bytes())
 | 
								trcLog = trcLog.RawJSON("response", lrr.body.Bytes())
 | 
				
			||||||
		} else {
 | 
							} else {
 | 
				
			||||||
			trcLog = trcLog.Bytes("response", lrr.body.Bytes())
 | 
								trcLog = trcLog.Bytes("response", lrr.body.Bytes())
 | 
				
			||||||
		}
 | 
							}
 | 
				
			||||||
		trcLog.Msg("response payload")
 | 
							trcLog.Msg("http response")
 | 
				
			||||||
	})
 | 
						})
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// Implement Flush to support the http.Flusher interface
 | 
					// Flush implements the http.Flusher interface to allow flushing buffered data.
 | 
				
			||||||
func (w *LoggingResponseWriter) Flush() {
 | 
					func (w *LoggingResponseWriter) Flush() {
 | 
				
			||||||
	if flusher, ok := w.ResponseWriter.(http.Flusher); ok {
 | 
						if flusher, ok := w.ResponseWriter.(http.Flusher); ok {
 | 
				
			||||||
		flusher.Flush()
 | 
							flusher.Flush()
 | 
				
			||||||
							
								
								
									
										88
									
								
								pkg/srv/http/http_test.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										88
									
								
								pkg/srv/http/http_test.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,88 @@
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
 | 
					package http
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"context"
 | 
				
			||||||
 | 
						"io"
 | 
				
			||||||
 | 
						"net/http"
 | 
				
			||||||
 | 
						"net/http/httptest"
 | 
				
			||||||
 | 
						"testing"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"github.com/stretchr/testify/assert"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"gitea.libretechconsulting.com/rmcguire/go-app/pkg/config"
 | 
				
			||||||
 | 
						"gitea.libretechconsulting.com/rmcguire/go-app/pkg/otel"
 | 
				
			||||||
 | 
						"gitea.libretechconsulting.com/rmcguire/go-app/pkg/srv/http/opts"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func TestInitHTTPServer(t *testing.T) {
 | 
				
			||||||
 | 
						cfg := &config.AppConfig{
 | 
				
			||||||
 | 
							Name: "test-app",
 | 
				
			||||||
 | 
							HTTP: &config.HTTPConfig{
 | 
				
			||||||
 | 
								Enabled: true,
 | 
				
			||||||
 | 
								Listen:  "127.0.0.1:0", // Use random available port
 | 
				
			||||||
 | 
							},
 | 
				
			||||||
 | 
							OTEL: &config.OTELConfig{
 | 
				
			||||||
 | 
								Enabled: true,
 | 
				
			||||||
 | 
							},
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						ctx := cfg.AddToCtx(context.Background())
 | 
				
			||||||
 | 
						ctx, _ = otel.Init(ctx)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						httpOpts := &opts.AppHTTP{
 | 
				
			||||||
 | 
							Ctx: ctx,
 | 
				
			||||||
 | 
							Funcs: []opts.HTTPFunc{
 | 
				
			||||||
 | 
								{
 | 
				
			||||||
 | 
									Path: "/test",
 | 
				
			||||||
 | 
									HandlerFunc: func(w http.ResponseWriter, r *http.Request) {
 | 
				
			||||||
 | 
										w.WriteHeader(http.StatusOK)
 | 
				
			||||||
 | 
									},
 | 
				
			||||||
 | 
								},
 | 
				
			||||||
 | 
							},
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						shutdown, done, err := InitHTTPServer(httpOpts)
 | 
				
			||||||
 | 
						assert.NoError(t, err)
 | 
				
			||||||
 | 
						assert.NotNil(t, shutdown)
 | 
				
			||||||
 | 
						assert.NotNil(t, done)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// Shutdown the server
 | 
				
			||||||
 | 
						err = shutdown(context.Background())
 | 
				
			||||||
 | 
						assert.NoError(t, err)
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func TestHealthCheck(t *testing.T) {
 | 
				
			||||||
 | 
						req := httptest.NewRequest("GET", "/health", nil)
 | 
				
			||||||
 | 
						w := httptest.NewRecorder()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						handleHealthCheckFunc(context.Background())(w, req)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						resp := w.Result()
 | 
				
			||||||
 | 
						body, _ := io.ReadAll(resp.Body)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						assert.Equal(t, http.StatusOK, resp.StatusCode)
 | 
				
			||||||
 | 
						assert.Equal(t, "ok", string(body))
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func TestLoggingMiddleware(t *testing.T) {
 | 
				
			||||||
 | 
						cfg := &config.AppConfig{
 | 
				
			||||||
 | 
							Name: "test-app",
 | 
				
			||||||
 | 
							HTTP: &config.HTTPConfig{
 | 
				
			||||||
 | 
								LogRequests: true,
 | 
				
			||||||
 | 
							},
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						ctx := cfg.AddToCtx(context.Background())
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 | 
				
			||||||
 | 
							w.WriteHeader(http.StatusOK)
 | 
				
			||||||
 | 
						})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						middleware := loggingMiddleware(ctx, handler)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						req := httptest.NewRequest("GET", "/test", nil)
 | 
				
			||||||
 | 
						w := httptest.NewRecorder()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						middleware.ServeHTTP(w, req)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						assert.Equal(t, http.StatusOK, w.Code)
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
							
								
								
									
										30
									
								
								pkg/srv/http/opts/http_config.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										30
									
								
								pkg/srv/http/opts/http_config.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,30 @@
 | 
				
			|||||||
 | 
					package opts
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"context"
 | 
				
			||||||
 | 
						"net"
 | 
				
			||||||
 | 
						"net/http"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					type AppHTTP struct {
 | 
				
			||||||
 | 
						Ctx            context.Context
 | 
				
			||||||
 | 
						Funcs          []HTTPFunc     // Handler funcs, will be wrapped with OTEL
 | 
				
			||||||
 | 
						Middleware     []http.Handler // Middleware (e.g. request logging)
 | 
				
			||||||
 | 
						Handlers       []HTTPHandler  // Raw Handler/Mux to add, optional prefix stripping
 | 
				
			||||||
 | 
						HealthChecks   []HealthCheckFunc
 | 
				
			||||||
 | 
						CustomListener net.Listener
 | 
				
			||||||
 | 
						HTTPDone       <-chan any
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					type HTTPFunc struct {
 | 
				
			||||||
 | 
						Path        string
 | 
				
			||||||
 | 
						HandlerFunc http.HandlerFunc
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					type HTTPHandler struct {
 | 
				
			||||||
 | 
						Prefix      string // path prefix under which to serve this handler/mux
 | 
				
			||||||
 | 
						StripPrefix bool   // strip path before sending to handler/mux
 | 
				
			||||||
 | 
						Handler     http.Handler
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					type HealthCheckFunc func(context.Context) error
 | 
				
			||||||
		Reference in New Issue
	
	Block a user