Comments (2)
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.
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:
from gf.
Related Issues (20)
- database/gdb: When (update/insert) operation, if the number of fields in the data table is 0, an error will be returned directly HOT 1
- os/gtime: There is a bug in converting string to gtime.Time HOT 3
- V2.7 cannot use ORM JSON storage HOT 2
- JetBrains OpenSourced Licenses - 2024 HOT 8
- cmd/gf: gen enums fail
- g.Dump: An error occurred during type serialization of json.MarshalJSON
- gf gen enums error report HOT 1
- gogf/gf: gen ctrl will also generate interface methods for the commented req&res HOT 1
- database/gdb: scan zero value for google.protobuf.Timestamp HOT 3
- db/gdb query table, field to cache
- There is a deadlock in gcache HOT 13
- codecov: runing ci-mail.sh failed
- util/gvalid: json array validation is invalid HOT 2
- cmd/gf: gf run how to exclude dir or file ?
- os/ghttp: stream流式输出可能存在bug HOT 2
- os/grpool: AddWithRecover Panic HOT 2
- os/gtime: issue config HOT 3
- gf gen dao use config database.default.link?
- The fields in the structure will not be set to default values when requesting HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from gf.