コード例 #1
0
func Server() {
	http.HandleFunc("/", app.Handler)
	defaultPort := 80
	defaultLimit := 50
	port := defaultPort
	limit := defaultLimit
	f := flag.NewFlagSet(os.Args[0], flag.ExitOnError)
	f.IntVar(&port, "p", defaultPort, "listen port")
	f.IntVar(&port, "port", defaultPort, "listen port")
	f.IntVar(&limit, "l", defaultLimit, "server limit")
	f.IntVar(&limit, "limit", defaultLimit, "server limit")
	f.Parse(os.Args[1:])
	for 0 < f.NArg() {
		f.Parse(f.Args()[1:])
	}
	addr := fmt.Sprintf(":%d", port)
	listener, err := net.Listen("tcp", addr)
	if err != nil {
		log.Fatalln(err)
	}

	limit_listener := netutil.LimitListener(listener, limit)
	defer limit_listener.Close()

	http_config := &http.Server{
		Handler: AccessLog(http.DefaultServeMux),
	}
	err = http_config.Serve(limit_listener)
	if err != nil {
		log.Fatalln(err)
	}
}
コード例 #2
0
ファイル: http.go プロジェクト: d0ngw/go
// Start 启动Http服务,开始端口监听和服务处理
func (self *HttpService) Start() bool {
	self.Lock()
	defer self.Unlock()

	c.Infof("Listen at %s", self.Conf.Addr)
	ln, err := net.Listen("tcp", self.Conf.Addr)
	if err != nil {
		c.Errorf("Listen at %s fail,error:%v", self.Conf.Addr, err)
		return false
	}

	tcpListener := tcpKeepAliveListener{ln.(*net.TCPListener)}
	if self.Conf.MaxConns > 0 {
		self.listener = netutil.LimitListener(tcpListener, self.Conf.MaxConns)
	} else {
		self.listener = tcpListener
	}

	self.graceHandler.waitGroup.Add(1)

	go func() {
		defer self.graceHandler.waitGroup.Done()
		err := self.server.Serve(self.listener)
		if err != nil {
			c.Errorf("server.Serve return with error:%v", err)
		}
	}()
	return true
}
コード例 #3
0
ファイル: server.go プロジェクト: go-microservices/resizer
func Start() error {
	t := log.Start()
	defer log.End(t)

	o, err := option.New(os.Args[1:])
	if err != nil {
		return err
	}
	handler, err := NewHandler(o)
	if err != nil {
		return err
	}
	s := http.Server{
		Handler:        &handler,
		ReadTimeout:    10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	l, err := net.Listen("tcp", addr)
	if err != nil {
		return err
	}
	if err := s.Serve(netutil.LimitListener(l, o.MaxConn)); err != nil {
		log.Fatalf("fail: err=%v", err)
	}
	log.Println("listening: addr=%s", addr)
	return nil
}
コード例 #4
0
ファイル: daemon.go プロジェクト: masahide/fastpass
func (d *Daemon) Serve(ctx context.Context) error {

	go d.QueryHandleWorker(ctx)
	for i := 0; i < d.WorkerLimit; i++ {
		d.MngQ[i] = make(chan ManageRequest, 1)
		go d.Worker(ctx, d.MngQ[i])
	}

	mux := http.NewServeMux()
	mux.HandleFunc("/query/", d.JsonHandler)
	mux.HandleFunc("/json/", d.JsonHandler)
	s := &http.Server{
		Addr:           d.Listen,
		Handler:        mux,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	listener, err := net.Listen("tcp", d.Listen)
	if err != nil {
		log.Fatalln(err)
	}
	log.Printf("listen: %s", d.Listen)
	//err = s.ListenAndServe()
	err = s.Serve(netutil.LimitListener(listener, d.ListenLimit))
	if err != nil {
		log.Printf("ListenAndServe err:%s", err)
	}
	return err
}
コード例 #5
0
ファイル: main.go プロジェクト: aimicm/nsqclient
///http服务器
func StartHttpServer() {
	fmt.Printf("HttpServer Run...\n")

	//静态目录
	http.Handle("/css/", http.FileServer(http.Dir("template")))
	http.Handle("/js/", http.FileServer(http.Dir("template")))

	//页面路由
	http.HandleFunc("/index.html", controller.IndexHandler)
	http.HandleFunc("/home.html", controller.HomeHandler)
	http.HandleFunc("/", controller.NotFoundHandler)

	///API接口路由
	http.HandleFunc("/SendMsg/", controller.PostMsgHandler)
	http.HandleFunc("/GetMsg/", controller.GetMsgHandler)

	http.HandleFunc("/ReceiveMsg/", controller.RevMsgHandler)
	http.HandleFunc("/ConMsq/", controller.ConMsqHandler)
	http.HandleFunc("/InfoMsq/", controller.InfoMsqHandler)

	//http.ListenAndServe(":8080", nil)
	///启动监听服务
	l, err := net.Listen("tcp", ":8080")
	if err != nil {
		fmt.Printf("Listen: %v", err)
	}
	defer l.Close()
	l = netutil.LimitListener(l, 1000000) //最大连接数

	http.Serve(l, nil)

}
コード例 #6
0
ファイル: revproxy.go プロジェクト: artyom/revproxy
func Listen(addr string, maxconn int) (net.Listener, error) {
	if maxconn < 1 {
		return nil, errors.New("maxconn should be positive")
	}
	ln, err := net.Listen("tcp", addr)
	if err != nil {
		return nil, err
	}
	return netutil.LimitListener(ln, maxconn), nil
}
コード例 #7
0
ファイル: graceful.go プロジェクト: pschlump/graceful
// Serve is equivalent to http.Server.Serve with graceful shutdown enabled.
func (srv *Server) Serve(listener net.Listener) error {

	if srv.ListenLimit != 0 {
		listener = netutil.LimitListener(listener, srv.ListenLimit)
	}

	// Track connection state
	add := make(chan net.Conn)
	remove := make(chan net.Conn)

	srv.Server.ConnState = func(conn net.Conn, state http.ConnState) {
		switch state {
		case http.StateNew:
			add <- conn
		case http.StateClosed, http.StateHijacked:
			remove <- conn
		}
		if srv.ConnState != nil {
			srv.ConnState(conn, state)
		}
	}

	// Manage open connections
	shutdown := make(chan chan struct{})
	kill := make(chan struct{})
	go srv.manageConnections(add, remove, shutdown, kill)

	interrupt := srv.interruptChan()
	// Set up the interrupt handler
	if !srv.NoSignalHandling {
		signal.Notify(interrupt, syscall.SIGINT, syscall.SIGTERM)
	}
	quitting := make(chan struct{})
	go srv.handleInterrupt(interrupt, quitting, listener)

	// Serve with graceful listener.
	// Execution blocks here until listener.Close() is called, above.
	err := srv.Server.Serve(listener)
	if err != nil {
		// If the underlying listening is closed, Serve returns an error
		// complaining about listening on a closed socket. This is expected, so
		// let's ignore the error if we are the ones who explicitly closed the
		// socket.
		select {
		case <-quitting:
			err = nil
		default:
		}
	}

	srv.shutdown(shutdown, kill)

	return err
}
コード例 #8
0
ファイル: service.go プロジェクト: messagedb/messagedb
// Open starts the service
func (s *Service) Open() error {
	// Open listener.
	listener, err := net.Listen("tcp", s.addr)
	if err != nil {
		return err
	}

	s.listener = netutil.LimitListener(listener, s.maxConn)

	s.Logger.Println("listening on HTTP:", listener.Addr().String())

	// Begin listening for requests in a separate goroutine.
	go s.serve()
	return nil
}
コード例 #9
0
ファイル: graceful.go プロジェクト: iron-io/imagelayers
// ListenAndServe is equivalent to http.Server.ListenAndServe with graceful shutdown enabled.
func (srv *Server) ListenAndServe() error {
	// Create the listener so we can control their lifetime
	addr := srv.Addr
	if addr == "" {
		addr = ":http"
	}
	l, err := net.Listen("tcp", addr)
	if err != nil {
		return err
	}

	if srv.ListenLimit != 0 {
		l = netutil.LimitListener(l, srv.ListenLimit)
	}
	return srv.Serve(l)
}
コード例 #10
0
ファイル: web.go プロジェクト: prometheus/prometheus
// Run serves the HTTP endpoints.
func (h *Handler) Run() {
	log.Infof("Listening on %s", h.options.ListenAddress)
	server := &http.Server{
		Addr:        h.options.ListenAddress,
		Handler:     h.router,
		ErrorLog:    log.NewErrorLogger(),
		ReadTimeout: h.options.ReadTimeout,
	}
	listener, err := net.Listen("tcp", h.options.ListenAddress)
	if err != nil {
		h.listenErrCh <- err
	} else {
		limitedListener := netutil.LimitListener(listener, h.options.MaxConnections)
		h.listenErrCh <- server.Serve(limitedListener)
	}
}
コード例 #11
0
ファイル: daemon.go プロジェクト: shingetsu-gou/shingetsu-gou
//StartDaemon setups saves pid, start cron job and a http server.
func StartDaemon() (net.Listener, chan error) {
	p := os.Getpid()
	err := ioutil.WriteFile(cfg.PID(), []byte(strconv.Itoa(p)), 0666)
	if err != nil {
		log.Fatal(err)
	}

	h := fmt.Sprintf("0.0.0.0:%d", cfg.DefaultPort)
	listener, err := net.Listen("tcp", h)
	if err != nil {
		log.Fatalln(err)
	}
	limitListener := netutil.LimitListener(listener, cfg.MaxConnection)
	sm := cgi.NewLoggingServeMux()
	s := &http.Server{
		Addr:           h,
		Handler:        sm,
		ReadTimeout:    3 * time.Minute,
		WriteTimeout:   3 * time.Minute,
		MaxHeaderBytes: 1 << 20,
	}

	go cron()

	admin.Setup(sm)
	server.Setup(sm)
	gateway.Setup(sm)
	thread.Setup(sm)

	if cfg.Enable2ch {
		fmt.Println("started 2ch interface...")
		mch.Setup(sm)
	}
	if cfg.EnableProf {
		sm.RegisterPprof()
	}
	sm.RegistCompressHandler("/", handleRoot())
	fmt.Println("started daemon and http server...")
	ch := make(chan error)
	go func() {
		ch <- s.Serve(limitListener)
	}()
	return limitListener, ch
}
コード例 #12
0
ファイル: graceful.go プロジェクト: jameswei/kingtask
// Serve is equivalent to http.Server.Serve with graceful shutdown enabled.
func (srv *Server) Serve(listener net.Listener) error {

	if srv.ListenLimit != 0 {
		listener = netutil.LimitListener(listener, srv.ListenLimit)
	}

	// Track connection state
	add := make(chan net.Conn)
	remove := make(chan net.Conn)

	srv.Server.ConnState = func(conn net.Conn, state http.ConnState) {
		switch state {
		case http.StateNew:
			add <- conn
		case http.StateClosed, http.StateHijacked:
			remove <- conn
		}
		if srv.ConnState != nil {
			srv.ConnState(conn, state)
		}
	}

	// Manage open connections
	shutdown := make(chan chan struct{})
	kill := make(chan struct{})
	go srv.manageConnections(add, remove, shutdown, kill)

	interrupt := srv.interruptChan()
	// Set up the interrupt handler
	if !srv.NoSignalHandling {
		signal.Notify(interrupt, syscall.SIGINT, syscall.SIGTERM)
	}
	go srv.handleInterrupt(interrupt, listener)

	// Serve with graceful listener.
	// Execution blocks here until listener.Close() is called, above.
	err := srv.Server.Serve(listener)

	srv.shutdown(shutdown, kill)

	return err
}
コード例 #13
0
ファイル: ip.go プロジェクト: delaemon/go-ip
func client() {
	http.HandleFunc("/", handler)
	listener, err := net.Listen("tcp", ":"+*p)
	if err != nil {
		log.Fatalln(err)
	}
	con, err := strconv.Atoi(*c)
	if err != nil {
		log.Fatalln(err)
	}
	limit_listener := netutil.LimitListener(listener, con)
	http_config := &http.Server{
		Handler: accessLog(http.DefaultServeMux),
	}
	defer limit_listener.Close()
	err = http_config.Serve(limit_listener)
	if err != nil {
		log.Fatalln(err)
	}
}
コード例 #14
0
ファイル: daemon.go プロジェクト: heartbeatsjp/happo-agent
// HTTPS Listener
func (l *daemonListener) listenAndServe() error {
	var err error

	cert := make([]tls.Certificate, 1)
	cert[0], err = tls.LoadX509KeyPair(l.PublicKey, l.PrivateKey)
	if err != nil {
		return err
	}

	tls_config := &tls.Config{
		CipherSuites: []uint16{
			tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
			// tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
			tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
		},
		PreferServerCipherSuites: true,
		MinVersion:               tls.VersionTLS12,
		NextProtos:               []string{"http/1.1"},
		Certificates:             cert,
	}

	listener, err := net.Listen("tcp", l.Port)
	if err != nil {
		return err
	}
	limit_listener := netutil.LimitListener(listener, l.MaxConnections)
	tls_listener := tls.NewListener(limit_listener, tls_config)

	http_config := &http.Server{
		TLSConfig:    tls_config,
		Addr:         l.Port,
		Handler:      l.Handler,
		ReadTimeout:  happo_agent.HTTP_TIMEOUT * time.Second,
		WriteTimeout: happo_agent.HTTP_TIMEOUT * time.Second,
	}

	return http_config.Serve(tls_listener)
}
コード例 #15
0
func Limited(port, limit string) {
	http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		w.WriteHeader(http.StatusOK)
		w.Header().Set("Content-Type", "text/plain")
		time.Sleep(time.Millisecond * 500) // for watch netstat
		io.WriteString(w, "Limited")
	})

	p, _ := strconv.Atoi(port)
	addr := fmt.Sprintf("localhost:%d", p)
	listener, err := net.Listen("tcp", addr)
	if err != nil {
		log.Fatalln(err)
	}
	l, _ := strconv.Atoi(limit)
	limit_listener := netutil.LimitListener(listener, l)
	http_config := &http.Server{}

	defer limit_listener.Close()
	err = http_config.Serve(limit_listener)
	if err != nil {
		log.Fatalln(err)
	}
}
コード例 #16
0
func CmdLimited(c *cli.Context) {
	http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		w.WriteHeader(http.StatusOK)
		w.Header().Set("Content-Type", "text/plain")
		time.Sleep(time.Millisecond * 500) // for watch netstat
		io.WriteString(w, "Limited")
	})

	port := fmt.Sprintf(":%d", c.Int("port"))
	listener, err := net.Listen("tcp", port)
	if err != nil {
		log.Fatalln(err)
	}
	limit_listener := netutil.LimitListener(listener, c.Int("max-connections"))
	http_config := &http.Server{
		Addr: port,
	}

	defer limit_listener.Close()
	err = http_config.Serve(limit_listener)
	if err != nil {
		log.Fatalln(err)
	}
}