本文整理汇总了Golang中net/http.Server.Handler方法的典型用法代码示例。如果您正苦于以下问题:Golang Server.Handler方法的具体用法?Golang Server.Handler怎么用?Golang Server.Handler使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类net/http.Server
的用法示例。
在下文中一共展示了Server.Handler方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: nextproto3
func nextproto3(s *Server, c *tls.Conn, h Handler) {
z := new(http.Server)
z.Addr = s.Addr
z.Handler = s.inner_h
z.ReadTimeout = s.ReadTimeout
z.WriteTimeout = s.WriteTimeout
z.MaxHeaderBytes = s.MaxHeaderBytes
if z.Handler == nil {
z.Handler = http.DefaultServeMux
}
server_session := spdy.NewServerSession(c, z)
server_session.Serve()
}
示例2: handleConnection
func (c *conn) handleConnection(outchan chan *Session) {
hserve := new(http.Server)
if c.srv.Handler == nil {
hserve.Handler = http.DefaultServeMux
} else {
hserve.Handler = c.srv.Handler
}
hserve.Addr = c.srv.Addr
c.ss = NewServerSession(c.cn, hserve)
if outchan != nil {
outchan <- c.ss
}
c.ss.Serve()
}
示例3: main
func main() {
port := 8080
var srv http.Server
router := mux.NewRouter()
router.HandleFunc("/hello", hello)
router.HandleFunc("/welcome", welcome)
router.PathPrefix("/").Handler(http.FileServer(http.Dir(".")))
srv.Addr = Sprintf(":%d", port)
/* set the http handler */
srv.Handler = &gpp.Handler{EnableProxy: true, Handler: router}
/* initial http2 support */
http2.ConfigureServer(&srv, nil)
log.Print("Listen on: ", Sprintf("https://0.0.0.0:%d", port))
srv.ListenAndServeTLS("server.crt", "server.key")
if err != nil {
log.Fatal(err)
}
}
示例4: Serve
func (e *endpoint) Serve() error {
// TODO: Currently only support single server per endpoint
if len(e.OriginServers) > 1 {
return errors.New("Currently only 1 origin server per endpoint is supported.")
}
// Create http2 server
var srv http.Server
// Set Port
srv.Addr = e.Address
// Mux setup
router := http.NewServeMux()
// Set mux
srv.Handler = router
// Set handlers
setHandlers(router, e)
err := http2.ConfigureServer(&srv, &http2.Server{})
if err != nil {
return err
}
log.Printf("Listening on %s", srv.Addr)
srv.ListenAndServeTLS(e.Certs.CertFile, e.Certs.KeyFile)
return nil
}
示例5: RunOnAddr
// Run the http server on a given host and port.
func (m *Martini) RunOnAddr(addr string) {
// TODO: Should probably be implemented using a new instance of http.Server in place of
// calling http.ListenAndServer directly, so that it could be stored in the martini struct for later use.
// This would also allow to improve testing when a custom host and port are passed.
logger := m.Injector.Get(reflect.TypeOf(m.logger)).Interface().(*log.Logger)
logger.Printf("listening on %s (%s)\n", addr, Env)
l, err := net.Listen("tcp", addr)
if err != nil {
logger.Fatalln(err.Error())
return
}
var server http.Server
server.Handler = m
server.ConnState = m.connectStateChange
m.server.l = l
go func() {
channel := m.server.stateChannel
for input := range channel {
switch input.state {
case http.StateNew, http.StateActive, http.StateIdle:
m.server.connsLock.Lock()
m.server.stateMap[input.conn] = input.state
m.server.connsLock.Unlock()
case http.StateHijacked, http.StateClosed:
m.server.connsLock.Lock()
delete(m.server.stateMap, input.conn)
m.server.connsLock.Unlock()
}
}
}()
server.Serve(l)
}
示例6: Start
func (s *fakeServer) Start(readyErrCh chan error) {
var err error
s.Listener, err = net.Listen("tcp", s.endpoint)
if err != nil {
readyErrCh <- err
return
}
readyErrCh <- nil
httpServer := http.Server{}
httpServer.SetKeepAlivesEnabled(false)
mux := http.NewServeMux()
httpServer.Handler = mux
mux.HandleFunc("/fake-path", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(s.responseStatus)
requestBody, _ := ioutil.ReadAll(r.Body)
defer r.Body.Close()
receivedRequest := receivedRequest{
Body: requestBody,
Method: r.Method,
}
s.ReceivedRequests = append(s.ReceivedRequests, receivedRequest)
w.Write([]byte(s.responseBody))
})
httpServer.Serve(s.Listener)
}
示例7: serveSmart
func (c *conn) serveSmart() {
defer func() {
if err := recover(); err != nil {
const size = 4096
buf := make([]byte, size)
buf = buf[:runtime.Stack(buf, false)]
log.Printf("http: panic serving %v: %v\n%s", c.remoteAddr, err, buf)
}
if !c.hijacked() {
c.close()
}
}()
if tlsConn, ok := c.rwc.(*tls.Conn); ok {
if d := c.server.ReadTimeout; d != 0 {
c.rwc.SetReadDeadline(time.Now().Add(d))
}
if d := c.server.WriteTimeout; d != 0 {
c.rwc.SetWriteDeadline(time.Now().Add(d))
}
if err := tlsConn.Handshake(); err != nil {
return
}
c.tlsState = new(tls.ConnectionState)
*c.tlsState = tlsConn.ConnectionState()
if proto := c.tlsState.NegotiatedProtocol; validNPN(proto) {
if fn := c.server.TLSNextProto[proto]; fn != nil {
h := initNPNRequest{tlsConn, serverHandler{c.server}}
fn(c.server, tlsConn, h)
}
return
}
}
initial_bytes := make([]byte, start_bytes)
// add smart detection
n, err := c.rwc.Read(initial_bytes)
if err != nil || n != start_bytes {
return
}
if checkspdy(initial_bytes) {
s := c.server
z := new(http.Server)
z.Addr = s.Addr
z.Handler = s.inner_h
z.ReadTimeout = s.ReadTimeout
z.WriteTimeout = s.WriteTimeout
z.MaxHeaderBytes = s.MaxHeaderBytes
server_session := spdy.NewServerSession(NewSmartConn(c.rwc, initial_bytes), z)
server_session.Serve()
return
}
c2, err := c.server.newConn(NewSmartConn(c.rwc, initial_bytes))
if err != nil {
return
}
c2.serve()
}
示例8: Start
func (t *WSTunnelServer) Start(listener net.Listener) {
t.Log.Info(VV)
if t.serverRegistry != nil {
return // already started...
}
t.serverRegistry = make(map[token]*remoteServer)
go t.idleTunnelReaper()
//===== HTTP Server =====
var httpServer http.Server
// Convert a handler that takes a tunnel as first arg to a std http handler
wrap := func(h func(t *WSTunnelServer, w http.ResponseWriter, r *http.Request)) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
h(t, w, r)
}
}
// Reqister handlers with default mux
httpMux := http.NewServeMux()
httpMux.HandleFunc("/", wrap(payloadHeaderHandler))
httpMux.HandleFunc("/_token/", wrap(payloadPrefixHandler))
httpMux.HandleFunc("/_tunnel", wrap(tunnelHandler))
httpMux.HandleFunc("/_health_check", wrap(checkHandler))
httpMux.HandleFunc("/_stats", wrap(statsHandler))
httpServer.Handler = httpMux
//httpServer.ErrorLog = log15Logger // would like to set this somehow...
// Read/Write timeouts disabled for now due to bug:
// https://code.google.com/p/go/issues/detail?id=6410
// https://groups.google.com/forum/#!topic/golang-nuts/oBIh_R7-pJQ
//ReadTimeout: time.Duration(cliTout) * time.Second, // read and idle timeout
//WriteTimeout: time.Duration(cliTout) * time.Second, // timeout while writing response
// Now create the listener and hook it all up
if listener == nil {
t.Log.Info("Listening", "port", t.Port)
laddr := fmt.Sprintf(":%d", t.Port)
var err error
listener, err = net.Listen("tcp", laddr)
if err != nil {
t.Log.Crit("Cannot listen", "addr", laddr)
os.Exit(1)
}
} else {
t.Log.Info("Listener", "addr", listener.Addr().String())
}
go func() {
t.Log.Debug("Server started")
httpServer.Serve(listener)
t.Log.Debug("Server ended")
}()
go func() {
<-t.exitChan
listener.Close()
}()
}
示例9: NewHostRouter
func NewHostRouter(httpServer *http.Server) *HostRouter {
r := &HostRouter{
Scheme: "http",
}
httpServer.Handler = r
r.server = httpServer
return r
}
示例10: main
func main() {
root := flag.String("r", "./testdata", "root of the directory to serve")
spdy_debug := flag.Bool("s", false, "enable SPDY debug output")
flag.Parse()
if *spdy_debug {
// enable spdy debug messages
spdy.EnableDebug()
}
for {
const SLEEP_RETRY = 5
var conn *tls.Conn
var err error
for i := 0; i < 10; i++ {
// connect to P.
conn, err = tls.Dial("tcp", HOST_PORT, &tls.Config{InsecureSkipVerify: true})
if err != nil {
time.Sleep(100 * time.Millisecond)
} else {
break
}
}
if conn == nil {
log.Println("Failed to connect. Waiting", SLEEP_RETRY, "seconds.")
time.Sleep(SLEEP_RETRY * time.Second)
continue
}
// build the request
buf := new(bytes.Buffer)
_, err = buf.WriteString("Hello from C")
handle(err)
req, err := http.NewRequest("PUT", "https://"+HOST_PORT, buf)
handle(err)
// make the client connection
client := httputil.NewClientConn(conn, nil)
res, err := client.Do(req)
if err != nil {
log.Println("Error: Failed to make connection to P:", err)
continue
}
buf.Reset()
_, err = io.Copy(buf, res.Body)
handle(err)
fmt.Printf("%q from P: %q.\n", res.Status, buf.String())
c, _ := client.Hijack()
conn = c.(*tls.Conn)
server := new(http.Server)
server.Handler = &handler{data: nil, rt: *root}
//http.FileServer(http.Dir(*root))
session := spdy.NewServerSession(conn, server)
session.Serve()
}
}
示例11: newServeWaiter
// newServeWaiter wraps srv in a serveWaiter.
func newServeWaiter(srv *http.Server) (t *serveWaiter) {
handler := srv.Handler
if handler == nil {
handler = http.DefaultServeMux
}
t = &serveWaiter{ServeCloser: NewServeCloser(srv)}
srv.Handler = &waitGroupHandler{srv: t, handler: handler}
return
}
示例12: run
func (e *Echo) run(s *http.Server, files ...string) {
s.Handler = e
if len(files) == 0 {
e.logger.Fatal(s.ListenAndServe())
} else if len(files) == 2 {
e.logger.Fatal(s.ListenAndServeTLS(files[0], files[1]))
} else {
e.logger.Fatal("invalid TLS configuration")
}
}
示例13: NewServer
/*
NewServer returns an intialized endlessServer Object. Calling Serve on it will
actually "start" the server.
*/
func NewServer(addr string, handler http.Handler) *endlessServer {
var srv http.Server
srv.Addr = addr
srv.ReadTimeout = DefaultReadTimeOut
srv.WriteTimeout = DefaultWriteTimeOut
srv.MaxHeaderBytes = DefaultMaxHeaderBytes
srv.Handler = handler
return New(srv)
}
示例14: ListenAndServeTLS
func (s *Http2Server) ListenAndServeTLS(config *tls.Config) error {
srv := http.Server{
Addr: s.Base.Node.Addr,
Handler: s.Handler,
TLSConfig: config,
}
if srv.Handler == nil {
srv.Handler = http.HandlerFunc(s.HandleRequest)
}
http2.ConfigureServer(&srv, nil)
return srv.ListenAndServeTLS("", "")
}
示例15: ListenAndServeTLS
func (context *Context) ListenAndServeTLS(port string, certFile string, keyFile string) {
var httpServer http.Server
httpServer.Addr = ":" + port
httpServer.Handler = http.HandlerFunc(serverHandler)
go func() {
err := httpServer.ListenAndServeTLS(certFile, keyFile)
if err != nil {
log.Printf("Listen error: %s", err)
}
}()
}