Skip to content

Commit

Permalink
add usage example
Browse files Browse the repository at this point in the history
Signed-off-by: Achille Roussel <[email protected]>
  • Loading branch information
achille-roussel committed Feb 1, 2024
1 parent e885f82 commit 27129cc
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 27129cc

Please sign in to comment.