Giter Site home page Giter Site logo

Comments (2)

yitiaoyu928 avatar yitiaoyu928 commented on May 21, 2024
package cmd

import (
	"context"
	"fmt"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/os/gcmd"
	"github.com/gorilla/websocket"
	"net/http"

	"demo-socket/internal/controller/hello"
)

var (
	update = websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}
)
var (
	Main = gcmd.Command{
		Name:  "main",
		Usage: "main",
		Brief: "start http server",
		Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {
			s := g.Server()
			s.Group("/", func(group *ghttp.RouterGroup) {
				group.ALL("/ws", func(http *ghttp.Request) {
					upgrade, err := update.Upgrade(http.Response.ResponseWriter, http.Request, nil)
					if err != nil {
						return
					}
					fmt.Println(upgrade)

				})
				group.Bind(
					hello.NewV1(),
				)
			})
			s.Run()
			return nil
		},
	}
)

from gf.

phuonganhniie avatar phuonganhniie commented on May 21, 2024

Hi @yitiaoyu928, I think the error you are encountering is due to an attempt to write headers on an already "hijacked" connection. This issue happens because WebSocket connections effectively take over the underlying HTTP connection, preventing further HTTP operations. That's means writing headers after the connection has been upgraded isn't allowed.

In the GoFrame, request.Response provides an abstraction over the standard http.ResponseWriter, adding extended functionality to control responses more efficiently. If you use request.Response.ResponseWriter directly, it's possible that internal GoFrame abstractions could interfere with the hijacked state, leading to the error. In GoFrame, request.Response.Writer provides direct access to the standard http.ResponseWriter, ensuring compatibility with third-party WebSocket libraries like gorilla/websocket.

This is my full code solution base on your code, hope it might be help you.

package cmd

import (
	"context"
	"fmt"
	"net/http"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/os/gcmd"
	"github.com/gorilla/websocket"

	"demo-socket/internal/controller/hello"
)

var (
	upgrader = websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
		CheckOrigin: func(r *http.Request) bool {
			return true 
		},
	}
)

var (
	Main = gcmd.Command{
		Name:  "main",
		Usage: "main",
		Brief: "start http server",
		Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {
			s := g.Server()

			s.Group("/", func(group *ghttp.RouterGroup) {
				group.ALL("/ws", func(request *ghttp.Request) {
					wsConn, err := upgrader.Upgrade(request.Response.Writer, request.Request, nil)
					if err != nil {
						request.Response.WriteHeader(http.StatusInternalServerError)
						return
					}
					defer wsConn.Close() // Ensure to close the connection when server is shutdown or crashed

					// Here, implement your WebSocket communication logic.
					// As an example, I'll just print a message and then close the connection.
					if err := wsConn.WriteMessage(websocket.TextMessage, []byte("Welcome to the WebSocket server!")); err != nil {
						fmt.Println("Write error:", err)
					}
				})

				group.Bind(
					hello.NewV1(),
				)
			})

			s.Run()
			return nil
		},
	}
)

Here is the the connection I tested by Postman:
Screenshot 2024-05-05 at 12 26 59

from gf.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.