Skip to content

How to set websocket to listen on tls? #2503

Open
@InfpHub

Description

@InfpHub

Describe the bug
A clear and concise description of what the bug is.

To Reproduce

package main

import (
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/websocket"
	"log"
	"strings"
)

func main() {
	// Upgrader 有两种
	// gorillaWs "github.com/gorilla/websocket"
	// 1. websocket.DefaultGobwasUpgrader
	// 2. websocket.DefaultGorillaUpgrader
	// 因为gorilla的upgrader有CheckOrigin限制,所以如果要使用gorilla, 需要使用如下
	// gorilla.Upgrader(gorillaWs.Upgrader{CheckOrigin: func(r *http.Request) bool { return true }})
	ws := websocket.New(websocket.DefaultGobwasUpgrader, websocket.Events{
		websocket.OnNativeMessage: func(nsConn *websocket.NSConn, msg websocket.Message) error {
			log.Printf("Server got: %s from [%s]", msg.Body, nsConn.Conn.ID())

			ping := string(msg.Body)
			pong := strings.Replace(ping, "?", "!", len(ping))
			pong = strings.Replace(pong, "么", "", len(pong))

			mg := websocket.Message{
				Body:     []byte(pong),
				IsNative: true,
			}

			nsConn.Conn.Write(mg)

			return nil
		},
	})

	ws.OnConnect = func(c *websocket.Conn) error {
		log.Printf("[%s] Connected to server!", c.ID())
		return nil
	}

	ws.OnDisconnect = func(c *websocket.Conn) {
		log.Printf("[%s] Disconnected from server", c.ID())
	}

	ws.OnUpgradeError = func(err error) {
		log.Printf("Upgrade Error: %v", err)
	}

	app := iris.New()
	app.HandleDir("/", "./html")
	app.Get("/msg", websocket.Handler(ws))

	app.Run(iris.TLS(":8080", "server.crt", "server.key"))
}
What I want to achieve is to provide grpc and websocket as the same service. grpc requires tls, and ordinary http does not work, but websocket does not seem to be able to use tls. For the front-end page, I don't have a forwarding like Nginx, or how to disable grpc's tls? I just want grpc and websocket to work at the same address at the same time

Desktop (please complete the following information):

  • OS: Windows 10

iris.Version

  • v12.2.5

Please make sure the bug is reproducible over the main branch:

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions