Skip to content

Commit

Permalink
Elide port in example
Browse files Browse the repository at this point in the history
  • Loading branch information
MarcoPolo committed Jul 19, 2024
1 parent 540b096 commit 9fef381
Showing 1 changed file with 12 additions and 2 deletions.
14 changes: 12 additions & 2 deletions p2p/http/example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"log"
"net"
"net/http"
"regexp"
"strings"

"github.com/libp2p/go-libp2p"
Expand Down Expand Up @@ -126,6 +127,15 @@ func ExampleHost_overLibp2pStreams() {
// Output: Hello HTTP
}

var portRe = regexp.MustCompile(`/(tcp|udp)/(?P<port>\d+)/http`)

// Given a multiaddr string, return the multiaddr with port filled in as <port>.
// Useful for showing examples without hardcoding the port.
func elidePort(addr string) string {
port := portRe.FindStringSubmatch(addr)[2]
return strings.Replace(addr, port, "<port>", 1)
}

func ExampleHost_Serve() {
server := libp2phttp.Host{
InsecureAllowHTTP: true, // For our example, we'll allow insecure HTTP
Expand All @@ -143,9 +153,9 @@ func ExampleHost_Serve() {
defer func() { <-serveDone }()
defer server.Close()

fmt.Println(server.Addrs())
fmt.Println(elidePort(server.Addrs()[0].String()))

// Output: [/ip4/127.0.0.1/tcp/50221/http]
// Output: /ip4/127.0.0.1/tcp/<port>/http
}

func ExampleHost_SetHTTPHandler() {
Expand Down

0 comments on commit 9fef381

Please sign in to comment.