• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang netutil.LimitListener函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中golang.org/x/net/netutil.LimitListener函数的典型用法代码示例。如果您正苦于以下问题:Golang LimitListener函数的具体用法?Golang LimitListener怎么用?Golang LimitListener使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了LimitListener函数的16个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: Server

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)
	}
}
开发者ID:delaemon,项目名称:go-gibson-serial-number,代码行数:32,代码来源:server.go


示例2: Start

// 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
}
开发者ID:d0ngw,项目名称:go,代码行数:30,代码来源:http.go


示例3: Start

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
}
开发者ID:go-microservices,项目名称:resizer,代码行数:27,代码来源:server.go


示例4: Serve

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
}
开发者ID:masahide,项目名称:fastpass,代码行数:30,代码来源:daemon.go


示例5: StartHttpServer

///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)

}
开发者ID:aimicm,项目名称:nsqclient,代码行数:33,代码来源:main.go


示例6: Listen

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
}
开发者ID:artyom,项目名称:revproxy,代码行数:10,代码来源:revproxy.go


示例7: Serve

// 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
}
开发者ID:pschlump,项目名称:graceful,代码行数:55,代码来源:graceful.go


示例8: Open

// 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
}
开发者ID:messagedb,项目名称:messagedb,代码行数:16,代码来源:service.go


示例9: ListenAndServe

// 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)
}
开发者ID:iron-io,项目名称:imagelayers,代码行数:17,代码来源:graceful.go


示例10: Run

// 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)
	}
}
开发者ID:prometheus,项目名称:prometheus,代码行数:17,代码来源:web.go


示例11: StartDaemon

//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
}
开发者ID:shingetsu-gou,项目名称:shingetsu-gou,代码行数:45,代码来源:daemon.go


示例12: Serve

// 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
}
开发者ID:jameswei,项目名称:kingtask,代码行数:43,代码来源:graceful.go


示例13: client

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)
	}
}
开发者ID:delaemon,项目名称:go-ip,代码行数:20,代码来源:ip.go


示例14: listenAndServe

// 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)
}
开发者ID:heartbeatsjp,项目名称:happo-agent,代码行数:39,代码来源:daemon.go


示例15: Limited

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)
	}
}
开发者ID:delaemon,项目名称:go-web-server-connection-limited,代码行数:24,代码来源:server.go


示例16: CmdLimited

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)
	}
}
开发者ID:koemu,项目名称:go-http-max-connections-demo,代码行数:24,代码来源:limited.go



注:本文中的golang.org/x/net/netutil.LimitListener函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang proxy.FromURL函数代码示例发布时间:2022-05-28
下一篇:
Golang ipv6.ICMPFilter类代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap