本文整理汇总了Golang中golang.org/x/net/websocket.Conn.Request方法的典型用法代码示例。如果您正苦于以下问题:Golang Conn.Request方法的具体用法?Golang Conn.Request怎么用?Golang Conn.Request使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类golang.org/x/net/websocket.Conn
的用法示例。
在下文中一共展示了Conn.Request方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: WebsocketHandler
func WebsocketHandler(ws *websocket.Conn) {
key := ws.Request().Header.Get("Sec-Websocket-Key")
client := Client{ws, key}
Srv.register(client)
defer func() {
Srv.unregister(client)
}()
for {
msg := make([]byte, 512)
n, err := ws.Read(msg)
if err != nil {
break
}
var cmd Command
json.Unmarshal(msg[:n], &cmd)
log.Println(cmd.Event)
client.process(cmd)
}
}
示例2: SockServer
func SockServer(ws *websocket.Conn) {
var err error
var clientMessage string
// use []byte if websocket binary type is blob or arraybuffer
// var clientMessage []byte
defer func() {
if err = ws.Close(); err != nil {
log.Println("Websocket could not be closed", err.Error())
}
}()
client := ws.Request().RemoteAddr
log.Println("Client connected:", client)
sockCli := ClientConn{ws, client}
ActiveClients[sockCli] = 0
log.Println("Number of clients connected ...", len(ActiveClients))
for {
if err = Message.Receive(ws, &clientMessage); err != nil {
log.Println("Websocket Disconnected waiting", err.Error())
delete(ActiveClients, sockCli)
log.Println("Number of clients still connected ...", len(ActiveClients))
return
}
if len(clientMessage) > 0 {
clientMessage = sockCli.clientIP + " Said: " + clientMessage
for cs, _ := range ActiveClients {
if err = Message.Send(cs.websocket, clientMessage); err != nil {
log.Println("Could not send message to ", cs.clientIP, err.Error())
}
}
}
}
}
示例3: BuildConnection
func BuildConnection(ws *websocket.Conn) {
email := ws.Request().URL.Query().Get("email")
if email == "" {
return
}
onlineUser := &OnlineUser{
InRoom: runningActiveRoom,
Connection: ws,
Send: make(chan Message, 256),
UserInfo: &User{
Email: email,
Name: strings.Split(email, "@")[0],
Gravatar: libs.UrlSize(email, 20),
},
}
runningActiveRoom.OnlineUsers[email] = onlineUser
m := Message{
MType: STATUS_MTYPE,
UserStatus: UserStatus{
Users: runningActiveRoom.GetOnlineUsers(),
},
}
runningActiveRoom.Broadcast <- m
go onlineUser.PushToClient()
onlineUser.PullFromClient()
onlineUser.killUserResource()
}
示例4: websocketUploadServer
func websocketUploadServer(ws *websocket.Conn) {
dlId := ws.Request().URL.Path[len("/api/upload_ws/"):]
bf := GetBounceFile(dlId)
if bf == nil {
ws.Write([]byte("ERROR! Download with this ID does not exist."))
return
}
var dataBuffer [50000]byte // 50 KB arbitrary
total := 0
for {
numBytes, err := ws.Read(dataBuffer[:])
total += numBytes
dataCopy := append([]byte{}, dataBuffer[:numBytes]...)
bf.SendData(dataCopy)
if err == io.EOF {
break
}
if err != nil { // Oops!
ws.Write([]byte("ERROR! " + err.Error()))
break
}
ws.Write([]byte("OK"))
}
}
示例5: handleWss
func handleWss(wsconn *websocket.Conn) {
p := Responder{nil, wsconn.Request(), time.Now()}
serverIP := wsconn.Request().Header.Get("X-Server-IP")
conn, err := net.Dial("tcp", serverIP)
if err != nil {
p.errorLog(http.StatusInternalServerError, "Error connecting to '%s': %s", serverIP, err.Error())
wsconn.Close()
return
}
defer conn.Close()
defer wsconn.Close()
wsconn.PayloadType = websocket.BinaryFrame
t := ©Syncer{alive: true}
go p.CopyR2W(t, conn, wsconn, serverIP+" ws2vnc")
go p.CopyR2W(t, wsconn, conn, serverIP+" vnc2ws")
p.errorLog(http.StatusOK, "websocket started: '%s'", serverIP)
for t.IsAlive() {
time.Sleep(100 * time.Millisecond)
}
p.errorLog(http.StatusOK, "websocket closed: '%s'", serverIP)
}
示例6: ServeWebSocket
func ServeWebSocket(ws *websocket.Conn) {
segs := strings.Split(ws.Request().URL.Path, "/")
if len(segs) < 2 {
log.Println("No token in incoming request, dropped")
websocket.JSON.Send(ws, "No token in incoming request, dropped")
return
}
ak, err := LoadKey(segs[1])
if err != nil {
log.Println(err.Error())
websocket.JSON.Send(ws, err.Error())
return
}
if ak.UsageIsLimited() {
err = ak.ConsumeUsage()
if err != nil {
log.Println(err.Error())
websocket.JSON.Send(ws, err.Error())
return
}
}
socket := NewSocket(ak, ws)
go socket.ListenToRedis()
go socket.ListenToSocket()
socket.Wait()
}
示例7: handler
func (l *listener) handler(ws *websocket.Conn) {
l.lock.Lock()
if !l.running {
ws.Close()
l.lock.Unlock()
return
}
w := &wsPipe{ws: ws, addr: l.addr, proto: l.proto, open: true}
w.iswss = l.iswss
req := ws.Request()
w.props = make(map[string]interface{})
w.props[mangos.PropLocalAddr] = ws.LocalAddr()
w.props[mangos.PropRemoteAddr], _ = net.ResolveTCPAddr("tcp", req.RemoteAddr)
if l.iswss {
w.props[mangos.PropTlsConnState] = *req.TLS
}
w.wg.Add(1)
l.pending = append(l.pending, w)
l.cv.Broadcast()
l.lock.Unlock()
// We must not return before the socket is closed, because
// our caller will close the websocket on our return.
w.wg.Wait()
}
示例8: wslogsHandler
func (ws *WebSocketServer) wslogsHandler(w *websocket.Conn) {
source := w.Request().FormValue("source")
host := fmt.Sprintf("%s/%d", w.RemoteAddr().String(), time.Now().UnixNano())
defer func() {
log.Printf("[%s - %s] closing websocket conn", ws.name, w.RemoteAddr().String())
ws.b.DelSubscriber(host)
w.Close()
}()
log.Printf("[%s - %s] accepting websocket conn", ws.name, w.RemoteAddr().String())
r := make(chan *buffer.Event, recvBuffer)
ws.b.AddSubscriber(host, r)
for {
select {
case ev := <-r:
if len(source) > 0 {
if ev.Source != source {
continue
}
}
err := websocket.Message.Send(w, *ev.Text)
if err != nil {
log.Printf("[%s] error sending ws message: %v", w.RemoteAddr().String(), err.Error())
return
}
}
}
}
示例9: BuildConnection
func BuildConnection(ws *websocket.Conn) {
log.Info("BuildConnection()")
token := ws.Request().URL.Query().Get("token")
log.Debug(token)
var uci userConnectionInfo
err := validateToken(token, time.Now(), ws.RemoteAddr(), &uci)
if err != nil {
log.WithFields(log.Fields{
"error": err,
}).Error("validation error")
// how should this reply to the client?
return
}
onlineUser := &OnlineUser{
Connection: ws,
Uci: uci,
Send: make(chan envelope, 256),
}
runningRoom.Users[onlineUser] = true
go onlineUser.PushToClient()
onlineUser.PullFromClient()
delete(runningRoom.Users, onlineUser)
log.Info("tore down user connection")
}
示例10: addLogs
func addLogs(ws *websocket.Conn) {
var err error
defer func() {
data := map[string]interface{}{}
if err != nil {
data["error"] = err.Error()
log.Error(err.Error())
} else {
data["error"] = nil
}
msg, _ := json.Marshal(data)
ws.Write(msg)
ws.Close()
}()
req := ws.Request()
t := context.GetAuthToken(req)
if t == nil {
err = fmt.Errorf("wslogs: no token")
return
}
if t.GetAppName() != app.InternalAppName {
err = fmt.Errorf("wslogs: invalid token app name: %q", t.GetAppName())
return
}
err = scanLogs(ws)
if err != nil {
return
}
}
示例11: AppLogs
func AppLogs(ws *websocket.Conn) *httperr.Error {
app := mux.Vars(ws.Request())["app"]
header := ws.Request().Header
var err error
follow := true
if header.Get("Follow") == "false" {
follow = false
}
since := 2 * time.Minute
if s := header.Get("Since"); s != "" {
since, err = time.ParseDuration(s)
if err != nil {
return httperr.Errorf(403, "Invalid duration %s", s)
}
}
err = models.Provider().LogStream(app, ws, structs.LogStreamOptions{
Filter: header.Get("Filter"),
Follow: follow,
Since: time.Now().Add(-1 * since),
})
if err != nil {
if strings.HasSuffix(err.Error(), "write: broken pipe") {
return nil
}
return httperr.Server(err)
}
return nil
}
示例12: AppLogs
func AppLogs(ws *websocket.Conn) error {
defer ws.Close()
app := mux.Vars(ws.Request())["app"]
a, err := models.GetApp(app)
if awsError(err) == "ValidationError" {
return fmt.Errorf("no such app: %s", app)
}
if err != nil {
return err
}
logs := make(chan []byte)
done := make(chan bool)
a.SubscribeLogs(logs, done)
for data := range logs {
ws.Write(data)
}
return nil
}
示例13: addLogs
func addLogs(ws *websocket.Conn) {
var err error
defer func() {
msg := &errMsg{}
if err != nil {
msg.Error = err.Error()
log.Errorf("failure in logs webservice: %s", err)
}
websocket.JSON.Send(ws, msg)
ws.Close()
}()
req := ws.Request()
t := context.GetAuthToken(req)
if t == nil {
err = errors.Errorf("wslogs: no token")
return
}
if t.GetAppName() != app.InternalAppName {
err = errors.Errorf("wslogs: invalid token app name: %q", t.GetAppName())
return
}
err = scanLogs(ws)
if err != nil {
return
}
}
示例14: ircHandler
func ircHandler(ws *websocket.Conn) {
var err error
var clientmessage string
current := ClientConn{ws, ws.Request().RemoteAddr}
clients[current] = 0
fmt.Println("number of clients connected ", len(clients))
for {
if err = message.Receive(ws, &clientmessage); err != nil {
delete(clients, current)
fmt.Println("client disconnect,", len(clients), " clients remain")
return
}
clientmessage = "<" + hash(current.ip) + "> " + clientmessage
for cs, _ := range clients {
if err = message.Send(cs.websocket, clientmessage); err != nil {
fmt.Println("sending failed")
}
}
}
}
示例15: onConnectionOpened
/**
* Event -> On connection opened
*/
func (server *server) onConnectionOpened(conn *websocket.Conn) {
defer server.Close(conn)
log.Printf("Connection opened: %v", conn.Request().RemoteAddr)
client := NewClient(conn, server)
server.startClient(client)
}