Skip to content

Commit

Permalink
add usage example (#3)
Browse files Browse the repository at this point in the history
  • Loading branch information
achille-roussel authored Feb 1, 2024
2 parents e885f82 + 27129cc commit 1948349
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions example_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package netjail_test

import (
"context"
"errors"
"fmt"
"log"
"net/http"
"net/netip"

"github.com/stealthrocket/netjail"
)

func ExampleTransport() {
// This rule set only allows connecting to a private IPv4 network.
ctx := netjail.ContextWithRules(context.Background(),
&netjail.Rules{
Allow: []netip.Prefix{
netip.MustParsePrefix("10.0.0.0/8"),
},
},
)

client := &http.Client{
Transport: &netjail.Transport{
New: func() *http.Transport {
return http.DefaultTransport.(*http.Transport).Clone()
},
},
}

r, err := http.NewRequestWithContext(ctx, "GET", "http://localhost/", nil)
if err != nil {
log.Fatal(err)
}

if r, err := client.Do(r); err != nil {
if !errors.Is(err, netjail.ErrDenied) {
log.Fatal(err)
} else {
fmt.Println("Access Denied")
}
} else {
r.Body.Close()
fmt.Println("Access Granted")
}

// Output:
// Access Denied
}

0 comments on commit 1948349

Please sign in to comment.