本文整理匯總了Golang中code/google/com/p/go/net/websocket.Server.ServeHTTP方法的典型用法代碼示例。如果您正苦於以下問題:Golang Server.ServeHTTP方法的具體用法?Golang Server.ServeHTTP怎麽用?Golang Server.ServeHTTP使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類code/google/com/p/go/net/websocket.Server
的用法示例。
在下文中一共展示了Server.ServeHTTP方法的14個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: main
func main() {
// Init
messages = make(chan Message)
messageDB = make([]Message, 0)
sockets = make([]*websocket.Conn, 0)
socketsLock = sync.Mutex{}
err := DecodeFile("./messages.json", &messageDB)
if err != nil {
log.Println(err)
}
// Wait for messages to broadcast to all sockets
go WaitAndBroadcast()
// Handle socket
http.HandleFunc("/",
func(w http.ResponseWriter, req *http.Request) {
s := websocket.Server{Handler: websocket.Handler(HandleSocket)}
s.ServeHTTP(w, req)
})
if err := http.ListenAndServe(":1234", nil); err != nil {
log.Fatal("ListenAndServe:", err)
}
}
示例2: Start
// Start is used by server.go to start the rpc listener.
func (s *rpcServer) Start() {
if atomic.AddInt32(&s.started, 1) != 1 {
return
}
rpcsLog.Trace("Starting RPC server")
rpcServeMux := http.NewServeMux()
httpServer := &http.Server{
Handler: rpcServeMux,
// Timeout connections which don't complete the initial
// handshake within the allowed timeframe.
ReadTimeout: time.Second * rpcAuthTimeoutSeconds,
}
rpcServeMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Connection", "close")
r.Close = true
// Limit the number of connections to max allowed.
if s.limitConnections(w, r.RemoteAddr) {
return
}
// Keep track of the number of connected clients.
s.incrementClients()
defer s.decrementClients()
if _, err := s.checkAuth(r, true); err != nil {
jsonAuthFail(w, r, s)
return
}
jsonRPCRead(w, r, s)
})
// Websocket endpoint.
rpcServeMux.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
authenticated, err := s.checkAuth(r, false)
if err != nil {
http.Error(w, "401 Unauthorized.", http.StatusUnauthorized)
return
}
wsServer := websocket.Server{
Handler: websocket.Handler(func(ws *websocket.Conn) {
s.WebsocketHandler(ws, r.RemoteAddr, authenticated)
}),
}
wsServer.ServeHTTP(w, r)
})
for _, listener := range s.listeners {
s.wg.Add(1)
go func(listener net.Listener) {
rpcsLog.Infof("RPC server listening on %s", listener.Addr())
httpServer.Serve(listener)
rpcsLog.Tracef("RPC listener done for %s", listener.Addr())
s.wg.Done()
}(listener)
}
s.ntfnMgr.Start()
}
示例3: sendContinuousChangesByWebSocket
func (h *handler) sendContinuousChangesByWebSocket(inChannels base.Set, options db.ChangesOptions) error {
handler := func(conn *websocket.Conn) {
h.logStatus(101, "Upgrading to WebSocket protocol")
caughtUp := false
h.generateContinuousChanges(inChannels, options, func(changes []*db.ChangeEntry) error {
var data []byte
if changes != nil {
data, _ = json.Marshal(changes)
} else if !caughtUp {
caughtUp = true
data, _ = json.Marshal([]*db.ChangeEntry{})
} else {
data = []byte{}
}
_, err := conn.Write(data)
return err
})
conn.Close()
}
server := websocket.Server{
Handshake: func(*websocket.Config, *http.Request) error { return nil },
Handler: handler,
}
server.ServeHTTP(h.response, h.rq)
return nil
}
示例4: HandleFunc
func (c *channelTable) HandleFunc()func(w http.ResponseWriter, req *http.Request) {
handler:=func(ws *websocket.Conn){
// ws.JSON.re
// for {
// select {
// case value:=<-fromClient:
// // websocket.JSON.Send(ws,value)
// // ws.Read(msg)
// data,err:=easyjson.NewEasyJson(value)
// if err!=nil {
// panic("error")
// }
// fmt.Fprintf(ws,"%s",data)
//
// default:
// // JSON.Receive(ws,&data)
// // msg := make([]byte, 512)
// readdata,err:=easyjson.NewEasyJson(ws)
// if err!=nil {
// panic("error")
// }
//
// toClient<-readdata
//
// }
// }
}
return func (w http.ResponseWriter, req *http.Request) {
s := websocket.Server{Handler: websocket.Handler(handler)}
s.ServeHTTP(w, req)
}
}
示例5: initHttpHandle
//init single http handle
func initHttpHandle(pattern string, handler websocket.Handler) {
http.HandleFunc(pattern,
func(w http.ResponseWriter, req *http.Request) {
s := websocket.Server{Handler: websocket.Handler(handler)}
s.ServeHTTP(w, req)
})
}
示例6: ServeHTTP
// ServeHTTP will serve up connections as a websocket.
// Args for the HTTP request are as follows:
// includeEntity -> []string - lists entity tags to include in the response
// - tags may finish with a '*' to match a prefix e.g.: unit-mysql-*, machine-2
// - if none are set, then all lines are considered included
// includeModule -> []string - lists logging modules to include in the response
// - if none are set, then all lines are considered included
// excludeEntity -> []string - lists entity tags to exclude from the response
// - as with include, it may finish with a '*'
// excludeModule -> []string - lists logging modules to exclude from the response
// limit -> uint - show *at most* this many lines
// backlog -> uint
// - go back this many lines from the end before starting to filter
// - has no meaning if 'replay' is true
// level -> string one of [TRACE, DEBUG, INFO, WARNING, ERROR]
// replay -> string - one of [true, false], if true, start the file from the start
func (h *debugLogHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
server := websocket.Server{
Handler: func(socket *websocket.Conn) {
logger.Infof("debug log handler starting")
if err := h.authenticate(req); err != nil {
h.sendError(socket, fmt.Errorf("auth failed: %v", err))
socket.Close()
return
}
if err := h.validateEnvironUUID(req); err != nil {
h.sendError(socket, err)
socket.Close()
return
}
stream, err := newLogStream(req.URL.Query())
if err != nil {
h.sendError(socket, err)
socket.Close()
return
}
// Open log file.
logLocation := filepath.Join(h.logDir, "all-machines.log")
logFile, err := os.Open(logLocation)
if err != nil {
h.sendError(socket, fmt.Errorf("cannot open log file: %v", err))
socket.Close()
return
}
defer logFile.Close()
if err := stream.positionLogFile(logFile); err != nil {
h.sendError(socket, fmt.Errorf("cannot position log file: %v", err))
socket.Close()
return
}
// If we get to here, no more errors to report, so we report a nil
// error. This way the first line of the socket is always a json
// formatted simple error.
if err := h.sendError(socket, nil); err != nil {
logger.Errorf("could not send good log stream start")
socket.Close()
return
}
stream.start(logFile, socket)
go func() {
defer stream.tomb.Done()
defer socket.Close()
stream.tomb.Kill(stream.loop())
}()
if err := stream.tomb.Wait(); err != nil {
if err != maxLinesReached {
logger.Errorf("debug-log handler error: %v", err)
}
}
}}
server.ServeHTTP(w, req)
}
示例7: main
func main() {
// http.Handle("/echo", websocket.Handler(echoHandler))
http.Handle("/", http.FileServer(http.Dir("./")))
http.HandleFunc("/echo",
func(w http.ResponseWriter, req *http.Request) {
s := websocket.Server{Handler: websocket.Handler(echoHandler)}
s.ServeHTTP(w, req)
})
if err := http.ListenAndServe(":9999", nil); err != nil {
panic("ListenAndServe: " + err.Error())
}
}
示例8: Start
// Start is used by server.go to start the rpc listener.
func (s *rpcServer) Start() {
if atomic.AddInt32(&s.started, 1) != 1 {
return
}
rpcsLog.Trace("Starting RPC server")
rpcServeMux := http.NewServeMux()
httpServer := &http.Server{
Handler: rpcServeMux,
// Timeout connections which don't complete the initial
// handshake within the allowed timeframe.
ReadTimeout: time.Second * rpcAuthTimeoutSeconds,
}
rpcServeMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if _, err := s.checkAuth(r, true); err != nil {
jsonAuthFail(w, r, s)
return
}
w.Header().Set("Connection", "close")
jsonRPCRead(w, r, s)
})
rpcServeMux.HandleFunc("/wallet", func(w http.ResponseWriter, r *http.Request) {
authenticated, err := s.checkAuth(r, false)
if err != nil {
http.Error(w, "401 Unauthorized.", http.StatusUnauthorized)
return
}
wsServer := websocket.Server{
Handler: websocket.Handler(func(ws *websocket.Conn) {
s.walletReqsNotifications(ws, authenticated)
}),
}
wsServer.ServeHTTP(w, r)
})
for _, listener := range s.listeners {
s.wg.Add(1)
go func(listener net.Listener) {
rpcsLog.Infof("RPC server listening on %s", listener.Addr())
httpServer.Serve(listener)
rpcsLog.Tracef("RPC listener done for %s", listener.Addr())
s.wg.Done()
}(listener)
}
}
示例9: sendContinuousChangesByWebSocket
func (h *handler) sendContinuousChangesByWebSocket(inChannels base.Set, options db.ChangesOptions) error {
handler := func(conn *websocket.Conn) {
h.logStatus(101, "Upgraded to WebSocket protocol")
defer func() {
conn.Close()
base.LogTo("HTTP+", "#%03d: --> WebSocket closed", h.serialNumber)
}()
// Read changes-feed options from an initial incoming WebSocket message in JSON format:
if msg, err := readWebSocketMessage(conn); err != nil {
return
} else {
var channelNames []string
var err error
if _, options, _, channelNames, err = readChangesOptionsFromJSON(msg); err != nil {
return
}
if channelNames != nil {
inChannels, _ = channels.SetFromArray(channelNames, channels.ExpandStar)
}
}
options.Terminator = make(chan bool)
defer close(options.Terminator)
caughtUp := false
h.generateContinuousChanges(inChannels, options, func(changes []*db.ChangeEntry) error {
var data []byte
if changes != nil {
data, _ = json.Marshal(changes)
} else if !caughtUp {
caughtUp = true
data, _ = json.Marshal([]*db.ChangeEntry{})
} else {
data = []byte{}
}
_, err := conn.Write(data)
return err
})
}
server := websocket.Server{
Handshake: func(*websocket.Config, *http.Request) error { return nil },
Handler: handler,
}
server.ServeHTTP(h.response, h.rq)
return nil
}
示例10: apiHandler
func (srv *Server) apiHandler(w http.ResponseWriter, req *http.Request) {
reqNotifier := newRequestNotifier()
reqNotifier.join(req)
defer reqNotifier.leave()
wsServer := websocket.Server{
Handler: func(conn *websocket.Conn) {
srv.wg.Add(1)
defer srv.wg.Done()
// If we've got to this stage and the tomb is still
// alive, we know that any tomb.Kill must occur after we
// have called wg.Add, so we avoid the possibility of a
// handler goroutine running after Stop has returned.
if srv.tomb.Err() != tomb.ErrStillAlive {
return
}
if err := srv.serveConn(conn, reqNotifier); err != nil {
logger.Errorf("error serving RPCs: %v", err)
}
},
}
wsServer.ServeHTTP(w, req)
}
示例11: main
func main() {
http.Handle("/", http.FileServer(http.Dir("./webroot")))
http.HandleFunc("/tcpdump",
func(w http.ResponseWriter, req *http.Request) {
s := websocket.Server{Handler: websocket.Handler(tcpdumpHandler)}
s.ServeHTTP(w, req)
})
http.HandleFunc("/interfaces",
func(w http.ResponseWriter, req *http.Request) {
interfaces, _ := net.Interfaces()
response := []map[string]interface{}{}
for _, intf := range interfaces {
addrs, _ := intf.Addrs()
stringAddrs := []string{}
for _, addr := range addrs {
stringAddrs = append(stringAddrs, addr.String())
}
data := map[string]interface{}{
"name": intf.Name,
"addresses": stringAddrs,
"flags": strings.Split(intf.Flags.String(), "|"),
"MAC": intf.HardwareAddr.String(),
}
response = append(response, data)
}
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(map[string]interface{}{
"interfaces": response}); err != nil {
panic(err)
}
})
if err := http.ListenAndServe(":12345", nil); err != nil {
panic("ListenAndServe: " + err.Error())
}
}
示例12: channelHandleFunc
func channelHandleFunc(
fromClient chan interface{},
toClient chan interface{}) func(w http.ResponseWriter, req *http.Request) {
echoHandler := func(ws *websocket.Conn) {
// ws.JSON.re
for {
select {
case value := <-fromClient:
// websocket.JSON.Send(ws,value)
// ws.Read(msg)
data, err := easyjson.NewEasyJson(value)
if err != nil {
panic("error")
}
fmt.Fprintf(ws, "%s", data)
default:
// JSON.Receive(ws,&data)
// msg := make([]byte, 512)
readdata, err := easyjson.NewEasyJson(ws)
if err != nil {
panic("error")
}
toClient <- readdata
}
}
}
return func(w http.ResponseWriter, req *http.Request) {
s := websocket.Server{Handler: websocket.Handler(echoHandler)}
s.ServeHTTP(w, req)
}
}
示例13: apiRouter
func (self *MyHttpServer) apiRouter(w http.ResponseWriter, req *http.Request) error {
switch req.URL.Path {
case "/":
fmt.Fprintf(w, "HELO MOMONGA WORLD")
case "/pub":
reqParams, err := url.ParseQuery(req.URL.RawQuery)
if err != nil {
return nil
}
var topic string
var qos string
if topics, ok := reqParams["topic"]; ok {
topic = topics[0]
}
if qoss, ok := reqParams["qos"]; ok {
qos = qoss[0]
}
if qos == "" {
qos = "0"
}
readMax := int64(8192)
body, _ := ioutil.ReadAll(io.LimitReader(req.Body, readMax))
if len(body) < 1 {
return fmt.Errorf("body required")
}
rqos, _ := strconv.ParseInt(qos, 10, 32)
self.Engine.SendMessage(topic, []byte(body), int(rqos))
w.Write([]byte(fmt.Sprintf("OK")))
return nil
case "/stats":
return nil
case self.WebSocketMount:
s := websocket.Server{
Handler: websocket.Handler(func(ws *websocket.Conn) {
// need for binary frame
ws.PayloadType = 0x02
myconf := GetDefaultMyConfig()
myconf.MaxMessageSize = self.Engine.Config().Server.MessageSizeLimit
conn := NewMyConnection(myconf)
conn.SetMyConnection(ws)
conn.SetId(ws.RemoteAddr().String())
self.Engine.HandleConnection(conn)
}),
Handshake: func(config *websocket.Config, req *http.Request) (err error) {
config.Origin, err = websocket.Origin(config, req)
if err == nil && config.Origin == nil {
return fmt.Errorf("null origin")
}
if len(config.Protocol) > 1 {
config.Protocol = []string{"mqttv3.1"}
}
// これどっしよっかなー。もうちょっと楽に選択させたい
v := 0
for i := 0; i < len(config.Protocol); i++ {
switch config.Protocol[i] {
case "mqtt":
if v == 0 {
v = 1
}
case "mqttv3.1":
v = 2
default:
return fmt.Errorf("unsupported protocol")
}
}
switch v {
case 1:
config.Protocol = []string{"mqtt"}
case 2:
config.Protocol = []string{"mqttv3.1"}
}
return err
},
}
s.ServeHTTP(w, req)
default:
return fmt.Errorf("404 %s", req.URL.Path)
}
return nil
}
示例14: Start
// Start starts a HTTP server to provide standard RPC and extension
// websocket connections for any number of btcwallet frontends.
func (s *server) Start() {
// A duplicator for notifications intended for all clients runs
// in another goroutines. Any such notifications are sent to
// the allClients channel and then sent to each connected client.
//
// Use a sync.Once to insure no extra duplicators run.
go duplicateOnce.Do(clientResponseDuplicator)
log.Trace("Starting RPC server")
serveMux := http.NewServeMux()
const rpcAuthTimeoutSeconds = 10
httpServer := &http.Server{
Handler: serveMux,
// Timeout connections which don't complete the initial
// handshake within the allowed timeframe.
ReadTimeout: time.Second * rpcAuthTimeoutSeconds,
}
serveMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if err := s.checkAuth(r); err != nil {
log.Warnf("Unauthorized client connection attempt")
http.Error(w, "401 Unauthorized.", http.StatusUnauthorized)
return
}
s.ServeRPCRequest(w, r)
})
serveMux.HandleFunc("/frontend", func(w http.ResponseWriter, r *http.Request) {
authenticated := false
if err := s.checkAuth(r); err != nil {
// If auth was supplied but incorrect, rather than simply being
// missing, immediately terminate the connection.
if err != ErrNoAuth {
log.Warnf("Disconnecting improperly authorized websocket client")
http.Error(w, "401 Unauthorized.", http.StatusUnauthorized)
return
}
} else {
authenticated = true
}
// A new Server instance is created rather than just creating the
// handler closure since the default server will disconnect the
// client if the origin is unset.
wsServer := websocket.Server{
Handler: websocket.Handler(func(ws *websocket.Conn) {
s.WSSendRecv(ws, r.RemoteAddr, authenticated)
}),
}
wsServer.ServeHTTP(w, r)
})
for _, listener := range s.listeners {
s.wg.Add(1)
go func(listener net.Listener) {
log.Infof("RPCS: RPC server listening on %s", listener.Addr())
httpServer.Serve(listener)
log.Tracef("RPCS: RPC listener done for %s", listener.Addr())
s.wg.Done()
}(listener)
}
}