honojs / hono

Web framework built on Web Standards
https://hono.dev
MIT License
18.51k stars 522 forks source link

Able to use `upgradeWebSocket` like a stream #3005

Open nakasyou opened 2 months ago

nakasyou commented 2 months ago

What is the feature you are proposing?

I think accepting using upgradeWebSocket like a stream is good. For example:

import { Hono } from 'hono'
import { upgradeWebSocket } from '.....'

const app = new Hono()

app.get('/ws', c => {
  return upgradeWebSocket(c, {
    onOpen () {
      console.log('opened!')
    }
  })
})

Because user can write more flexible code such as creating custom response in WebSocket route.

Lucifer359-IV commented 2 months ago

but why a right minded person will create custom response on this kind of thing

nakasyou commented 2 months ago

Hi @Lucifer359-IV, for example, you can do that

app.get('/ws', c => {
  if (!validToken(c.req.query('token'))) {
    return c.text('Unauthorized', 400)
  }
  return upgradeWebSocket(c, {
    onOpen () {
      console.log('opened!')
    }
  })
})

Also you can change the response with or without the upgrade header.

JoaquimLey commented 2 months ago

@nakasyou can't you do that token validation with a middleware?

Also have you checked the streaming helper section in the docs?