本文整理汇总了Golang中github.com/gorilla/websocket.Upgrader类的典型用法代码示例。如果您正苦于以下问题:Golang Upgrader类的具体用法?Golang Upgrader怎么用?Golang Upgrader使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Upgrader类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: slashws
func slashws(w http.ResponseWriter, req *http.Request) {
// Upgrader.Upgrade() has Origin check if .CheckOrigin is nil
upgrader := gorillawebsocket.Upgrader{}
wsconn, err := upgrader.Upgrade(w, req, nil)
if err != nil { // Upgrade() does http.Error() to the client
return
}
// req.Method == "GET" asserted by the mux
req.Form = nil // reset reused later .Form
c := &conn{
Conn: wsconn,
requestOrigin: req,
receive: make(chan *received, 2),
push: make(chan *pageUpdate, 2),
full: defaultClient(),
}
register <- c
defer func() {
unregister <- c
c.Conn.Close()
}()
stop := make(chan struct{}, 1)
go c.receiveLoop(stop) // read from the client
c.updateLoop(stop) // write to the client
}
开发者ID:tomzhang,项目名称:golang-devops-stuff,代码行数:26,代码来源:ws.go
示例2: webSocket
func webSocket(res http.ResponseWriter, req *http.Request) {
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool { return true },
}
res.Header().Set("Access-Control-Allow-Origin", "*")
conn, err := upgrader.Upgrade(res, req, nil)
if err != nil {
log.Printf("Not a web socket connection: %s \n", err)
return
}
for {
messageType, p, err := conn.ReadMessage()
if err != nil {
return
}
if err = conn.WriteMessage(messageType, p); err != nil {
return
}
}
}
开发者ID:keuller,项目名称:gserver,代码行数:25,代码来源:gserver.go
示例3: IndexWS
func IndexWS(access *Access, errlog *log.Logger, minperiod flags.Period, w http.ResponseWriter, req *http.Request) {
// Upgrader.Upgrade() has Origin check if .CheckOrigin is nil
upgrader := gorillawebsocket.Upgrader{
HandshakeTimeout: 5 * time.Second,
}
wsconn, err := upgrader.Upgrade(w, req, nil)
if err != nil { // Upgrade() does http.Error() to the client
return
}
// req.Method == "GET" asserted by the mux
req.Form = nil // reset reused later .Form
c := &conn{
Conn: wsconn,
requestOrigin: req,
receive: make(chan *received, 2),
pushch: make(chan *IndexUpdate, 2),
para: params.NewParams(minperiod),
access: access,
}
Register <- c
defer func() {
unregister <- c
c.Conn.Close()
}()
stop := make(chan struct{}, 1)
go c.receiveLoop(stop) // read from the client
c.updateLoop(errlog, stop) // write to the client
}
开发者ID:vadv,项目名称:ostent,代码行数:31,代码来源:ws.go
示例4: Upgrade
func Upgrade(res http.ResponseWriter, req *http.Request) {
if req.Header["Origin"][0] != "http://localhost" {
return
}
up := websocket.Upgrader{
CheckOrigin: func(req *http.Request) bool {
if req.Header["Origin"][0] != "http://localhost" {
// return false
// gorilla stops the app if wrong origin...
}
return true
},
}
conn, err := up.Upgrade(res, req, nil)
if err != nil {
log.Fatal(err)
}
go hub.Handle(conn)
hub.H.Register <- &hub.Register{conn, time.Now().UnixNano()}
r, err := json.Marshal(&hub.BroadcastMessage{
0,
"User connected",
})
if err != nil {
log.Fatal(err)
}
hub.H.Broadcast <- &hub.Broadcast{
conn,
r,
"default",
}
}
开发者ID:Raggaer,项目名称:Gochatty,代码行数:32,代码来源:socket.go
示例5: Start
// Start the websocket server, each peer connecting to this websocket will be added as a connection to the dispatcher
func Start(d *Dispatcher, port int) {
var upgrader = websocket.Upgrader{
ReadBufferSize: 2048,
WriteBufferSize: 2048,
CheckOrigin: func(r *http.Request) bool {
return true
},
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
log.Debug("Connection received")
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
startConnection(conn, d)
})
go http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
log.Println(fmt.Sprintf("Websocket server started on port %d", port))
select {}
}
开发者ID:whouses,项目名称:rotonde,代码行数:26,代码来源:websocketconnection.go
示例6: live
func (w *webserver) live(resp http.ResponseWriter, req *http.Request) {
//get our feeder registered
wsf := &liveWSFeeder{
ch: make(chan namedBwSample, chanBufferSize),
}
id, err := w.lf.RegisterLiveFeeder(wsf)
if err != nil {
resp.WriteHeader(http.StatusInternalServerError)
return
}
defer w.lf.DeregisterLiveFeeder(id)
//upgrade to a websocket
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
conn, err := upgrader.Upgrade(resp, req, nil)
if err != nil {
return
}
defer conn.Close()
//start feeding and relaying
for s := range wsf.ch {
if err := websocket.WriteJSON(conn, s); err != nil {
break
}
}
}
开发者ID:traetox,项目名称:gobwmon,代码行数:30,代码来源:webserver.go
示例7: main
func main() {
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
http.Handle("/", handlers.LoggingHandler(os.Stderr, http.FileServer(http.Dir("."))))
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
defer conn.Close()
for {
t, msg, err := conn.ReadMessage()
if err != nil {
log.Println(err)
return
}
log.Println("Received:", string(msg))
err = conn.WriteMessage(t, msg)
if err != nil {
log.Println(err)
return
}
}
})
host := "localhost:3030"
log.Printf("http://%v", host)
log.Fatal(http.ListenAndServe(host, nil))
}
开发者ID:jakecoffman,项目名称:polymer-basics,代码行数:32,代码来源:server.go
示例8: consoleHandler
func consoleHandler(w http.ResponseWriter, r *http.Request) {
upgrader := websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
go wsReadLoop(conn)
defer conn.Close()
lines, done, err := tailFile(fOptions.LogPath)
if err != nil {
log.Println(err)
return
}
defer close(done)
for line := range lines {
err = conn.WriteMessage(websocket.TextMessage, append(line, '\n'))
if err != nil {
return
}
}
}
开发者ID:LA3QMA,项目名称:wl2k-go,代码行数:27,代码来源:http.go
示例9: ListenAndServe
// ListenAndServe will run a simple WS (HTTP) server.
// return listening error
func (s *Server) ListenAndServe(address string, path string) error {
l, err := net.Listen("tcp", address)
if err != nil {
return err
}
s.listener = l
mux := http.NewServeMux()
mux.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
var upgrader = websocket.Upgrader{
ReadBufferSize: s.readBufferSize,
WriteBufferSize: s.writeBufferSize,
CheckOrigin: func(r *http.Request) bool {
return true
},
}
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Print("upgrade:", err)
return
}
s.wsHandler.ServeWS(
conn.UnderlyingConn(),
newAbstractStream(conn),
r.URL.Query(),
)
})
s.httpHandler = mux
go s.serve()
return nil
}
开发者ID:escrichov,项目名称:websocket-server,代码行数:37,代码来源:server.go
示例10: handler
func (ws *webSocketRenderer) handler(w http.ResponseWriter, r *http.Request) {
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
h := http.Header{}
h["Sec-WebSocket-Protocol"] = []string{"nesrender"}
conn, err := upgrader.Upgrade(w, r, h)
if err != nil {
panic("Unable to upgrade connection")
}
ws.conns = append(ws.conns, conn)
for {
t, _, err := conn.ReadMessage()
if err != nil {
break
}
if t == websocket.CloseMessage {
break
}
}
}
开发者ID:evandigby,项目名称:nesgo,代码行数:28,代码来源:websocketrenderer.go
示例11: startMockAcsServer
func startMockAcsServer(t *testing.T, closeWS <-chan bool) (*httptest.Server, chan<- string, <-chan string, <-chan error, error) {
serverChan := make(chan string)
requestsChan := make(chan string)
errChan := make(chan error)
upgrader := websocket.Upgrader{ReadBufferSize: 1024, WriteBufferSize: 1024}
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ws, err := upgrader.Upgrade(w, r, nil)
go func() {
<-closeWS
ws.Close()
}()
if err != nil {
errChan <- err
}
go func() {
_, msg, err := ws.ReadMessage()
if err != nil {
errChan <- err
} else {
requestsChan <- string(msg)
}
}()
for str := range serverChan {
err := ws.WriteMessage(websocket.TextMessage, []byte(str))
if err != nil {
errChan <- err
}
}
})
server := httptest.NewTLSServer(handler)
return server, serverChan, requestsChan, errChan, nil
}
开发者ID:dockerstack,项目名称:amazon-ecs-agent,代码行数:34,代码来源:acs_client_test.go
示例12: Handle
func Handle(w http.ResponseWriter, r *http.Request) {
upgrader := websocket.Upgrader{
CheckOrigin: func(req *http.Request) bool {
if req.Host == "127.0.0.1:9090" {
return true
} else {
return false
}
},
}
var err error
WebSocketConn, err = upgrader.Upgrade(w, r, nil)
if err != nil {
utils.Errorf("Error upgrade http: %s", err.Error())
return
}
for {
mt, bytes, err := WebSocketConn.ReadMessage()
if err != nil {
utils.Errorf("Error read message: %v", err)
WebSocketConn.Close()
WebSocketConn = nil
return
}
utils.Debugf("Client msg received: %d, %s", mt, string(bytes))
}
}
开发者ID:hulucat,项目名称:welcome,代码行数:27,代码来源:websocket.go
示例13: ServeHTTP
func (f *FakeFirehose) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
f.lock.Lock()
defer f.lock.Unlock()
f.lastAuthorization = r.Header.Get("Authorization")
f.requested = true
if f.lastAuthorization != f.validToken {
log.Printf("Bad token passed to firehose: %s", f.lastAuthorization)
rw.WriteHeader(403)
r.Body.Close()
return
}
upgrader := websocket.Upgrader{
CheckOrigin: func(*http.Request) bool { return true },
}
ws, _ := upgrader.Upgrade(rw, r, nil)
defer ws.Close()
defer ws.WriteControl(websocket.CloseMessage, f.closeMessage, time.Time{})
for _, envelope := range f.events {
buffer, _ := proto.Marshal(&envelope)
err := ws.WriteMessage(websocket.BinaryMessage, buffer)
if err != nil {
panic(err)
}
}
f.wg.Wait()
}
开发者ID:pivotal-cf-experimental,项目名称:opentsdb-firehose-nozzle,代码行数:32,代码来源:fake_firehose.go
示例14: echo
func echo(w http.ResponseWriter, r *http.Request) {
// Upgrade from http to websocket protocol
upgrader := websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
panic(err)
}
defer c.Close()
for {
mt, message, err := c.ReadMessage()
if err != nil {
panic(err)
}
fmt.Printf("Received message: %s\n", message)
err = c.WriteMessage(mt, message)
if err != nil {
panic(err)
}
}
}
开发者ID:BenchR267,项目名称:websocket-playground,代码行数:27,代码来源:main.go
示例15: main
func main() {
upgrader := websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true
},
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
id, err := authentication.AuthenticateRequest(r.FormValue("AccessToken"))
if err != nil {
http.Error(w, err.Error(), 500)
return
}
if id == -1 {
http.Error(w, "", 401)
return
}
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Fatal(err)
}
c := client.New(id, conn)
router.AddClientChan <- c
go c.Run()
})
fmt.Println("listening on 8080")
http.ListenAndServe(":8080", nil)
}
开发者ID:pleniec,项目名称:pvpc-ws,代码行数:34,代码来源:main.go
示例16: WSServer
func WSServer(w http.ResponseWriter, req *http.Request) {
var upgrader = websocket.Upgrader{
ReadBufferSize: 64,
WriteBufferSize: 64,
}
conn, err := upgrader.Upgrade(w, req, nil)
if err != nil {
fmt.Println("ERROR:" + err.Error())
return
}
for {
messageType, r, err := conn.NextReader()
reader := bufio.NewReader(r)
b, err := reader.ReadBytes('\n')
response := []byte("ECHO FROM " + servername + ":" + string(b))
if err != nil {
fmt.Println("ERROR:" + err.Error())
return
}
// w, err := conn.NextWriter(messageType)
// if err != nil {
// fmt.Println("ERROR:"+err.Error())
// return
// }
if err := conn.WriteMessage(messageType, response); err != nil {
fmt.Println("ERROR:" + err.Error())
return
}
}
}
开发者ID:RealHacker,项目名称:kitchensink,代码行数:31,代码来源:echoserver.go
示例17: GetConnection
func GetConnection(rw http.ResponseWriter, req *http.Request) (*connection, error) {
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
upgrader.CheckOrigin = func(r *http.Request) bool {
// allow all connections by default
return true
}
conn := &connection{}
for _, v := range req.Header["Connection"] {
for _, i := range strings.Split(v, ",") {
if strings.EqualFold(strings.TrimSpace(i), "upgrade") {
webConn, err := upgrader.Upgrade(rw, req, nil)
if err != nil {
return nil, err
}
conn.webConn = webConn
return conn, nil
}
}
}
conn.rw = rw
return conn, nil
}
开发者ID:wlan0,项目名称:host-api,代码行数:30,代码来源:conn.go
示例18: wsHandler
func wsHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("wshandler")
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Print("upgrade:", err)
return
}
defer conn.Close()
if err != nil {
log.Println(err)
return
}
for {
messageType, message, err := conn.ReadMessage()
if err != nil {
return
}
log.Print(message)
err = conn.WriteMessage(messageType, []byte(strings.Join(getdrives(), ",")))
if err != nil {
return
}
}
}
开发者ID:subiron,项目名称:WebCommander,代码行数:32,代码来源:server.go
示例19: fakeFirehoseHandler
func fakeFirehoseHandler(rw http.ResponseWriter, r *http.Request) {
defer GinkgoRecover()
authorization := r.Header.Get("Authorization")
if authorization != "bearer good-token" {
log.Printf("Bad token passed to firehose: %s", authorization)
rw.WriteHeader(403)
r.Body.Close()
return
}
upgrader := websocket.Upgrader{
CheckOrigin: func(*http.Request) bool { return true },
}
ws, _ := upgrader.Upgrade(rw, r, nil)
defer ws.Close()
defer ws.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""), time.Time{})
for envelope := range fakeFirehoseInputChan {
buffer, err := proto.Marshal(envelope)
Expect(err).NotTo(HaveOccurred())
err = ws.WriteMessage(websocket.BinaryMessage, buffer)
Expect(err).NotTo(HaveOccurred())
}
}
开发者ID:pivotal-cf-experimental,项目名称:opentsdb-firehose-nozzle,代码行数:27,代码来源:opentsdb_firehose_nozzle_test.go
示例20: NewSockets
// NewSockets returns a new websocket port
func NewSockets(upgrader *websocket.Upgrader, headers http.Header, hs SocketHandler) FlatChains {
return NewFlatChain(func(c *Context, nx NextHandler) {
if headers != nil {
origin, ok := c.Req.Header["Origin"]
if ok {
headers.Set("Access-Control-Allow-Credentials", "true")
headers.Set("Access-Control-Allow-Origin", strings.Join(origin, ";"))
} else {
headers.Set("Access-Control-Allow-Origin", "*")
}
}
conn, err := upgrader.Upgrade(c.Res, c.Req, headers)
if err != nil {
return
}
flux.GoDefer(fmt.Sprintf("WebSocketPort.Handler"), func() {
hs(NewSocketWorker(&Websocket{
Conn: conn,
Ctx: c,
}))
nx(c)
})
})
}
开发者ID:influx6,项目名称:todo,代码行数:30,代码来源:sockets.go
注:本文中的github.com/gorilla/websocket.Upgrader类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论