Skip to content

Commit 93629f2

Browse files
authored
Merge pull request #20 from Treblle/feat/exclude-routes
Introduce excludedRoutes feature
2 parents b78f1fd + 0d25adb commit 93629f2

8 files changed

Lines changed: 998 additions & 103 deletions

LICENSE

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
MIT License
22

3-
Copyright (c) 2021 treblle
3+
Copyright (c) 2021 Treblle
44

55
Permission is hereby granted, free of charge, to any person obtaining a copy
66
of this software and associated documentation files (the "Software"), to deal

README.md

Lines changed: 90 additions & 101 deletions
Original file line numberDiff line numberDiff line change
@@ -1,66 +1,47 @@
1-
# Treblle
1+
# Treblle - API Intelligence Platform
22

3-
![Treblle Logo](https://github.com/user-attachments/assets/54f0c084-65bb-4431-b80d-cceab6c63dc3 "Treblle Logo")
3+
[![Treblle API Intelligence](https://github.com/user-attachments/assets/b268ae9e-7c8a-4ade-95da-b4ac6fce6eea)](https://treblle.com)
44

5-
[Integrations](https://docs.treblle.com/en/integrations)
6-
[Website](http://treblle.com/)
7-
[Docs](https://docs.treblle.com)
8-
[Blog](https://blog.treblle.com)
9-
[Twitter](https://twitter.com/treblleapi)
10-
[Discord](https://treblle.com/chat)
5+
[Website](http://treblle.com/)[Documentation](https://docs.treblle.com/)[Pricing](https://treblle.com/pricing)
116

12-
---
13-
14-
API Intelligence Platform.
15-
16-
Treblle is a lightweight SDK that helps Engineering and Product teams build, ship & maintain REST-based APIs faster.
17-
18-
## Features
19-
20-
![Treblle Features](https://github.com/user-attachments/assets/9b5f40ba-bec9-414b-af88-f1c1cc80781b "Treblle Features")
21-
22-
- [API Monitoring & Observability](https://www.treblle.com/features/api-monitoring-observability)
23-
- [Auto-generated API Docs](https://www.treblle.com/features/auto-generated-api-docs)
24-
- [API analytics](https://www.treblle.com/features/api-analytics)
25-
- [Treblle API Score](https://www.treblle.com/features/api-quality-score)
26-
- [API Lifecycle Collaboration](https://www.treblle.com/features/api-lifecycle)
27-
- [Native Treblle Apps](https://www.treblle.com/features/native-apps)
28-
29-
## How Treblle Works
30-
31-
Once you've integrated a Treblle SDK in your codebase, this SDK will send requests and response data to your Treblle Dashboard.
32-
33-
In your Treblle Dashboard you get to see real-time requests to your API, auto-generated API docs, API analytics like how fast the response was for an endpoint, the load size of the response, etc.
34-
35-
Treblle also uses the requests sent to your Dashboard to calculate your API score which is a quality score that's calculated based on the performance, quality, and security best practices for your API.
36-
37-
> Visit [https://docs.treblle.com](http://docs.treblle.com) for the complete documentation.
7+
Treblle is an API intelligence platfom that helps developers, teams and organizations understand their APIs from a single integration point.
388

39-
## Security
40-
41-
### Masking fields
42-
43-
Masking fields ensure certain sensitive data are removed before being sent to Treblle.
9+
---
4410

45-
To make sure masking is done before any data leaves your server [we built it into all our SDKs](https://docs.treblle.com/en/security/masked-fields#fields-masked-by-default).
11+
## Treblle Go Lang SDK
4612

47-
This means data masking is super fast and happens on a programming level before the API request is sent to Treblle. You can [customize](https://docs.treblle.com/en/security/masked-fields#custom-masked-fields) exactly which fields are masked when you're integrating the SDK.
13+
### Requirements
4814

49-
> Visit the [Masked fields](https://docs.treblle.com/en/security/masked-fields) section of the [docs](https://docs.sailscasts.com) for the complete documentation.
15+
| Go Version | Support Status |
16+
|------------|----------------|
17+
| 1.23+ | Fully Supported |
18+
| 1.21 - 1.22 | Should work, not officially tested |
19+
| < 1.21 | Not Supported |
5020

51-
## Get Started
21+
### Router & Framework Support
5222

53-
1. Sign in to [Treblle](https://platform.treblle.com).
54-
2. [Create a Treblle project](https://docs.treblle.com/en/dashboard/projects#creating-a-project).
55-
3. [Setup the SDK](#installation) for your platform.
23+
| Router/Framework | Support Level | Native Integration |
24+
|------------------|---------------|-------------------|
25+
| **Standard Library** (`net/http`) | Fully Supported | Yes |
26+
| **Gin** | Fully Supported | Yes |
27+
| **Gorilla Mux** | ✅ Fully Supported | Yes |
28+
| **Chi** | Fully Supported | Yes |
29+
| **Echo** | Compatible | No |
30+
| **Fiber** | Compatible | No |
31+
| **Other Routers** | Compatible | No |
5632

5733
## Installation
5834

35+
### 1. Install the Package
36+
5937
```bash
6038
go get github.com/Treblle/treblle-go/v2
6139
```
6240

63-
## Configuration
41+
### 2. Get Your Credentials
42+
Get your SDK Token and API Key from the [Treblle Dashboard](https://platform.treblle.com).
43+
44+
### 3. Configure Treblle
6445

6546
```go
6647
import (
@@ -72,14 +53,12 @@ func main() {
7253
SDK_TOKEN: "your-treblle-sdk-token",
7354
API_KEY: "your-treblle-api-key",
7455
})
75-
56+
7657
// Your API server setup
7758
// ...
7859
}
7960
```
8061

81-
## Usage with Different Routers
82-
8362
### With Gin
8463

8564
The SDK provides native support for the Gin framework with automatic route pattern extraction:
@@ -181,77 +160,87 @@ router.GET("/users/:id", wrapHandler(treblle.WithRoutePath("/users/:id",
181160
treblle.Middleware(http.HandlerFunc(getUserHandler)))))
182161
```
183162

184-
## Manual Route Path Setting
163+
## Excluding Routes
185164

186-
You can also set route paths programmatically in your handlers:
165+
You can configure Treblle to exclude specific routes from being tracked. This is useful for health checks, metrics endpoints, internal APIs, or any routes you don't want to monitor.
166+
167+
### Basic Usage
187168

188169
```go
189-
func myHandler(w http.ResponseWriter, r *http.Request) {
190-
// Set the route path for this specific request
191-
r = treblle.SetRoutePath(r, "/api/custom/:param")
192-
193-
// Your handler logic
194-
// ...
195-
}
170+
treblle.Configure(treblle.Configuration{
171+
SDK_TOKEN: "your-treblle-sdk-token",
172+
API_KEY: "your-treblle-api-key",
173+
ExcludedRoutes: []string{
174+
"/health", // Exact match
175+
"/metrics", // Exact match
176+
"/admin/*", // Wildcard: matches all admin routes
177+
"/api/*/internal/*", // Multiple wildcards
178+
},
179+
})
196180
```
197181

198-
## Examples
199-
200-
Check the `examples` directory for complete example applications:
182+
### Pattern Types
201183

202-
- `gorilla_example`: Shows integration with Gorilla Mux
203-
- `standard_example`: Shows integration with the standard HTTP package
184+
**Exact Match:**
185+
```go
186+
ExcludedRoutes: []string{"/health", "/status", "/readiness"}
187+
```
188+
- Matches exactly `/health`, `/status`, and `/readiness`
189+
- Case-insensitive matching
190+
- Trailing slashes are normalized (`/health/` matches `/health`)
204191

205-
## Available SDKs
192+
**Simple Wildcard:**
193+
```go
194+
ExcludedRoutes: []string{"/admin/*"}
195+
```
196+
- Matches `/admin/dashboard`, `/admin/users`, `/admin/users/123`, etc.
197+
- The `*` matches any segment and **all nested paths**
198+
- Perfect for excluding entire sections of your API
206199

207-
Treblle provides [open-source SDKs](https://docs.treblle.com/en/integrations) that let you seamlessly integrate Treblle with your REST-based APIs.
200+
**Multiple Wildcards:**
201+
```go
202+
ExcludedRoutes: []string{
203+
"/api/*/internal/*",
204+
"/v*/debug/*",
205+
}
206+
```
207+
- Each `*` matches exactly one path segment
208+
- `/api/*/internal/*` matches `/api/v1/internal/debug`, `/api/v2/internal/metrics/detailed`, etc.
209+
- Provides fine-grained control over exclusions
208210

209-
- [`treblle-laravel`](https://github.com/Treblle/treblle-laravel): SDK for Laravel
210-
- [`treblle-php`](https://github.com/Treblle/treblle-php): SDK for PHP
211-
- [`treblle-symfony`](https://github.com/Treblle/treblle-symfony): SDK for Symfony
212-
- [`treblle-lumen`](https://github.com/Treblle/treblle-lumen): SDK for Lumen
213-
- [`treblle-sails`](https://github.com/Treblle/treblle-sails): SDK for Sails
214-
- [`treblle-adonisjs`](https://github.com/Treblle/treblle-adonisjs): SDK for AdonisJS
215-
- [`treblle-fastify`](https://github.com/Treblle/treblle-fastify): SDK for Fastify
216-
- [`treblle-directus`](https://github.com/Treblle/treblle-directus): SDK for Directus
217-
- [`treblle-strapi`](https://github.com/Treblle/treblle-strapi): SDK for Strapi
218-
- [`treblle-express`](https://github.com/Treblle/treblle-express): SDK for Express
219-
- [`treblle-koa`](https://github.com/Treblle/treblle-koa): SDK for Koa
220-
- [`treblle-go`](https://github.com/Treblle/treblle-go): SDK for Go
221-
- [`treblle-ruby`](https://github.com/Treblle/treblle-ruby): SDK for Ruby on Rails
222-
- [`treblle-python`](https://github.com/Treblle/treblle-python): SDK for Python/Django
211+
### Environment Variable
223212

224-
> See the [docs](https://docs.treblle.com/en/integrations) for more on SDKs and Integrations.
213+
You can also set excluded routes via environment variable:
214+
```bash
215+
export TREBLLE_EXCLUDED_ROUTES="/health,/metrics,/admin/*"
216+
```
225217

226-
## Other Packages
218+
The environment variable uses comma-separated values and is loaded automatically if `ExcludedRoutes` is not set in the configuration.
227219

228-
Besides the SDKs, we also provide helpers and configuration used for SDK
229-
development. If you're thinking about contributing to or creating a SDK, have a look at the resources
230-
below:
231220

232-
- [`treblle-utils`](https://github.com/Treblle/treblle-utils): A set of helpers and
233-
utility functions useful for the JavaScript SDKs.
234-
- [`php-utils`](https://github.com/Treblle/php-utils): A set of helpers and
235-
utility functions useful for the PHP SDKs.
221+
## Examples
236222

237-
## Community
223+
Check the `examples` directory for complete example applications:
238224

239-
First and foremost: **Star and watch this repository** to stay up-to-date.
225+
- `gorilla_example`: Shows integration with Gorilla Mux
226+
- `standard_example`: Shows integration with the standard HTTP package
240227

241-
Also, follow our [Blog](https://blog.treblle.com), and on [Twitter](https://twitter.com/treblleapi).
242228

243-
You can chat with the team and other members on [Discord](https://treblle.com/chat) and follow our tutorials and other video material at [YouTube](https://youtube.com/@treblle).
229+
## Getting Help
244230

245-
[![Treblle Discord](https://img.shields.io/badge/Treblle%20Discord-Join%20our%20Discord-F3F5FC?labelColor=7289DA&style=for-the-badge&logo=discord&logoColor=F3F5FC&link=https://treblle.com/chat)](https://treblle.com/chat)
231+
If you continue to experience issues:
246232

247-
[![Treblle YouTube](https://img.shields.io/badge/Treblle%20YouTube-Subscribe%20on%20YouTube-F3F5FC?labelColor=c4302b&style=for-the-badge&logo=YouTube&logoColor=F3F5FC&link=https://youtube.com/@treblle)](https://youtube.com/@treblle)
233+
1. Enable `debug: true` and check console output
234+
2. Verify your SDK token and API key are correct in Treblle dashboard
235+
3. Test with a simple endpoint first
236+
4. Check [Treblle documentation](https://docs.treblle.com) for the latest updates
237+
5. Contact support at <https://treblle.com> or email support@treblle.com
248238

249-
[![Treblle on Twitter](https://img.shields.io/badge/Treblle%20on%20Twitter-Follow%20Us-F3F5FC?labelColor=1DA1F2&style=for-the-badge&logo=Twitter&logoColor=F3F5FC&link=https://twitter.com/treblleapi)](https://twitter.com/treblleapi)
239+
## Support
250240

251-
### How to contribute
241+
If you have problems of any kind feel free to reach out via <https://treblle.com> or email support@treblle.com and we'll do our best to help you out.
252242

253-
Here are some ways of contributing to making Treblle better:
243+
## License
254244

255-
- **[Try out Treblle](https://docs.treblle.com/en/introduction#getting-started)**, and let us know ways to make Treblle better for you. Let us know here on [Discord](https://treblle.com/chat).
256-
- Join our [Discord](https://treblle.com/chat) and connect with other members to share and learn from.
257-
- Send a pull request to any of our [open source repositories](https://github.com/Treblle) on Github. Check the contribution guide on the repo you want to contribute to for more details about how to contribute. We're looking forward to your contribution!
245+
Copyright 2025, Treblle Inc. Licensed under the MIT license:
246+
http://www.opensource.org/licenses/mit-license.php

configuration.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package treblle
22

33
import (
4+
"fmt"
45
"os"
56
"strconv"
67
"strings"
@@ -26,6 +27,7 @@ type Configuration struct {
2627
MaxConcurrentProcessing int // Maximum number of concurrent async operations (default: 10)
2728
AsyncShutdownTimeout time.Duration // Timeout for async shutdown (default: 5s)
2829
IgnoredEnvironments []string // Environments where Treblle does not track requests
30+
ExcludedRoutes []string // Routes that Treblle should not track
2931
Debug bool // Enable debug mode to see what's being sent to Treblle
3032
}
3133

@@ -48,6 +50,8 @@ type internalConfiguration struct {
4850
MaxConcurrentProcessing int
4951
AsyncShutdownTimeout time.Duration
5052
IgnoredEnvironments []string
53+
ExcludedRoutes []string
54+
compiledExclusions *compiledRoutePatterns // Pre-compiled patterns for performance
5155
}
5256

5357
func Configure(config Configuration) {
@@ -133,6 +137,25 @@ func Configure(config Configuration) {
133137
Config.IgnoredEnvironments = getEnvAsSlice("TREBLLE_IGNORED_ENV", defaultIgnoredEnvs)
134138
}
135139

140+
// Load excluded routes from config or environment variable
141+
if len(config.ExcludedRoutes) > 0 {
142+
Config.ExcludedRoutes = config.ExcludedRoutes
143+
} else {
144+
Config.ExcludedRoutes = getEnvAsSlice("TREBLLE_EXCLUDED_ROUTES", []string{})
145+
}
146+
147+
// Pre-compile route exclusion patterns for efficient matching
148+
Config.compiledExclusions = compileRoutePatterns(Config.ExcludedRoutes)
149+
150+
// Debug: Log excluded routes if debug mode is enabled
151+
if Config.Debug && len(Config.ExcludedRoutes) > 0 {
152+
fmt.Printf("==== TREBLLE: EXCLUDED ROUTES ====\n")
153+
for _, route := range Config.ExcludedRoutes {
154+
fmt.Printf(" - %s\n", route)
155+
}
156+
fmt.Printf("==================================\n")
157+
}
158+
136159
Config.FieldsMap = generateFieldsToMask(Config.DefaultFieldsToMask, Config.AdditionalFieldsToMask)
137160
}
138161

gin_middleware.go

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,22 @@ func GinMiddleware() gin.HandlerFunc {
3737
return
3838
}
3939

40+
// Check if route is excluded
41+
routePath := c.FullPath()
42+
if routePath == "" {
43+
routePath = c.Request.URL.Path
44+
}
45+
normalizedRoute := normalizeRoutePath(routePath)
46+
47+
if Config.compiledExclusions != nil && isRouteExcluded(normalizedRoute, Config.compiledExclusions) {
48+
if Config.Debug {
49+
fmt.Printf("==== TREBLLE GIN: ROUTE EXCLUDED ====\nRoute: %s\n=====================================\n", normalizedRoute)
50+
}
51+
// Skip Treblle logging for excluded routes
52+
c.Next()
53+
return
54+
}
55+
4056
// Create error provider for this request
4157
errorProvider := NewErrorProvider()
4258
defer errorProvider.Clear()
@@ -60,7 +76,7 @@ func GinMiddleware() gin.HandlerFunc {
6076
c.Request = tracker.StoreStartTime(c.Request)
6177

6278
// Extract route pattern from Gin (e.g., "/users/:id")
63-
routePath := c.FullPath()
79+
routePath = c.FullPath()
6480
if routePath != "" {
6581
c.Request = SetRoutePath(c.Request, routePath)
6682
}

middleware.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,22 @@ func Middleware(next http.Handler) http.Handler {
1717
return
1818
}
1919

20+
// Check if route is excluded
21+
routePath := GetRoutePath(r)
22+
if routePath == "" {
23+
routePath = r.URL.Path
24+
}
25+
normalizedRoute := normalizeRoutePath(routePath)
26+
27+
if Config.compiledExclusions != nil && isRouteExcluded(normalizedRoute, Config.compiledExclusions) {
28+
if Config.Debug {
29+
fmt.Printf("==== TREBLLE: ROUTE EXCLUDED ====\nRoute: %s\n=================================\n", normalizedRoute)
30+
}
31+
// Skip Treblle logging for excluded routes
32+
next.ServeHTTP(w, r)
33+
return
34+
}
35+
2036
// Create error provider for this request
2137
errorProvider := NewErrorProvider()
2238
defer errorProvider.Clear()

0 commit comments

Comments
 (0)