Skip to content

Commit

Permalink
Add Hono example
Browse files Browse the repository at this point in the history
  • Loading branch information
MarcoPolo committed Jun 7, 2024
1 parent 98982ad commit 55abf19
Show file tree
Hide file tree
Showing 3 changed files with 126 additions and 0 deletions.
59 changes: 59 additions & 0 deletions examples/hono-server-over-libp2p/client.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { noise } from '@chainsafe/libp2p-noise'
import { multiaddr } from '@multiformats/multiaddr'
import { yamux } from '@chainsafe/libp2p-yamux'
import { tcp } from '@libp2p/tcp'
import { createLibp2p } from 'libp2p'
import { http } from '../../dist/src/index.js'
import { sendPing } from '../../dist/src/ping.js'

const node = await createLibp2p({
// libp2p nodes are started by default, pass false to override this
start: false,
addresses: {
listen: []
},
transports: [tcp()],
connectionEncryption: [noise()],
streamMuxers: [yamux()],
services: { http: http() }
})

// start libp2p
await node.start()
console.error('libp2p has started')

// Read server multiaddr from the command line
const serverAddr = process.argv[2]
if (!serverAddr) {
console.error('Please provide the server multiaddr as an argument')
process.exit(1)
}

let serverMA = multiaddr(serverAddr)

const isHTTPTransport = serverMA.protos().find(p => p.name === "http") // check if this is an http transport multiaddr
if (!isHTTPTransport && serverMA.getPeerId() === null) {
// Learn the peer id of the server. This lets us reuse the connection for all our HTTP requests.
// Otherwise js-libp2p will open a new connection for each request.
const conn = await node.dial(serverMA)
serverMA = serverMA.encapsulate(`/p2p/${conn.remotePeer.toString()}`)
}

console.error("Making request to", `${serverMA.toString()}`)
try {
const resp = await node.services.http.fetch(new Request(`multiaddr:${serverMA}` + `/http-path/${encodeURIComponent('my-app')}`))
const respBody = await resp.text()
if (resp.status !== 200) {
throw new Error(`Unexpected status code: ${resp.status}`)
}
if (respBody !== 'Hono!') {
throw new Error(`Unexpected response body: ${respBody}`)
}

const start = new Date().getTime()
await sendPing(node, serverMA)
const end = new Date().getTime()
console.error("HTTP Ping took", end - start, "ms")
} finally {
await node.stop()
}
65 changes: 65 additions & 0 deletions examples/hono-server-over-libp2p/server.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { noise } from '@chainsafe/libp2p-noise'
import { yamux } from '@chainsafe/libp2p-yamux'
import { tcp } from '@libp2p/tcp'
import { createLibp2p } from 'libp2p'
import { WELL_KNOWN_PROTOCOLS, http, httpCustomServer } from '../../dist/src/index.js'
import { PING_PROTOCOL_ID, servePing } from '../../dist/src/ping.js'
import { Hono } from 'hono'
import { serve } from '@hono/node-server'

const app = new Hono()

const node = await createLibp2p({
// libp2p nodes are started by default, pass false to override this
start: false,
addresses: {
listen: ['/ip4/127.0.0.1/tcp/8000']
},
transports: [tcp()],
connectionEncryption: [noise()],
streamMuxers: [yamux()],
services: {http: httpCustomServer({customHTTPHandler: app.fetch.bind(app)})}
})

app.get(WELL_KNOWN_PROTOCOLS, async (c) => {
return node.services.http.serveWellKnownProtocols(c.req)
})
app.get('/my-app', (c) => c.text('Hono!'))
node.services.http.registerProtocol('/example-app/0.0.1', "/my-app")

// Register HTTP ping protocol
app.all('/ping', (c) => {
return servePing(c.req)
})
node.services.http.registerProtocol(PING_PROTOCOL_ID, "/ping")

// start libp2p
await node.start()
console.error('libp2p has started')

// Also listen on a standard http transport
const server = serve({
fetch: app.fetch,
port: 8001,
hostname: '127.0.0.1',
})

const listenAddrs = node.getMultiaddrs()
console.error('libp2p is listening on the following addresses:')
console.log(`/ip4/127.0.0.1/tcp/8001/http`)
for (const addr of listenAddrs) {
console.log(addr.toString())
}
console.log("") // Empty line to signal we have no more addresses (for test runner)


// wait for SIGINT
await new Promise(resolve => process.on('SIGINT', resolve))

// Stop the http server
server.close()

// stop libp2p
node.stop()
console.error('libp2p has stopped')

2 changes: 2 additions & 0 deletions examples/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@
"dependencies": {
"@chainsafe/libp2p-noise": "^15.0.0",
"@chainsafe/libp2p-yamux": "^6.0.2",
"@hono/node-server": "^1.11.2",
"@libp2p/tcp": "^9.0.26",
"@multiformats/multiaddr": "^12.3.0",
"@multiformats/multiaddr-to-uri": "^10.1.0",
"hono": "^4.4.4",
"libp2p": "^1.6.0"
},
"license": "Apache-2.0 OR MIT"
Expand Down

0 comments on commit 55abf19

Please sign in to comment.