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

Golang fasthttp.ListenAndServe函数代码示例

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

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



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

示例1: main

func main() {
	runtime.GOMAXPROCS(2)
	// pass bound struct method to fasthttp
	myHandler := &MyHandler{
		foobar: "foobar",
	}

	fmt.Println("Hello World!")
	fasthttp.ListenAndServe(":8080", myHandler.HandleFastHTTP)
	//pass plain function to fasthttp
	fasthttp.ListenAndServe(":8081", fastHTTPHandler)
}
开发者ID:kazarus,项目名称:GoDemo,代码行数:12,代码来源:main.go


示例2: ExampleRequestCtx_TimeoutError

func ExampleRequestCtx_TimeoutError() {
	requestHandler := func(ctx *fasthttp.RequestCtx) {
		// Emulate long-running task, which touches ctx.
		doneCh := make(chan struct{})
		go func() {
			workDuration := time.Millisecond * time.Duration(rand.Intn(2000))
			time.Sleep(workDuration)

			fmt.Fprintf(ctx, "ctx has been accessed by long-running task\n")
			fmt.Fprintf(ctx, "The reuqestHandler may be finished by this time.\n")

			close(doneCh)
		}()

		select {
		case <-doneCh:
			fmt.Fprintf(ctx, "The task has been finished in less than a second")
		case <-time.After(time.Second):
			// Since the long-running task is still running and may access ctx,
			// we must call TimeoutError before returning from requestHandler.
			//
			// Otherwise the program will suffer from data races.
			ctx.TimeoutError("Timeout!")
		}
	}

	if err := fasthttp.ListenAndServe(":80", requestHandler); err != nil {
		log.Fatalf("error in ListenAndServe: %s", err)
	}
}
开发者ID:xiaoma20082008,项目名称:fasthttp,代码行数:30,代码来源:server_example_test.go


示例3: main

func main() {
	router := fasthttprouter.New()
	router.GET("/", Index)
	router.GET("/hello/:name", Hello)

	log.Fatal(fasthttp.ListenAndServe(":8080", router.Handler))
}
开发者ID:Anon-Penguin,项目名称:fasthttprouter,代码行数:7,代码来源:basic.go


示例4: main

func main() {

	port := flag.Int("p", 8080, "http port")
	flag.Parse()

	pprofMux := http.NewServeMux()
	registerPProf(pprofMux.HandleFunc)
	fastpprof := fasthttpadaptor.NewFastHTTPHandler(pprofMux)

	requestHandler := func(ctx *fasthttp.RequestCtx) {
		switch {
		case bytes.Equal(ctx.Path(), []byte("/debug/pprof")):
			ctx.Redirect("/debug/pprof/", 301)
		case bytes.HasPrefix(ctx.Path(), []byte("/debug/pprof/")):
			fastpprof(ctx)
		default:
			ctx.NotFound()
		}
	}

	log.Println("listening on port", *port)

	err := fasthttp.ListenAndServe(":"+strconv.Itoa(*port), requestHandler)
	if err != nil {
		log.Println("error during fasthttp.ListenAndServe(): ", err)
	}
}
开发者ID:dgryski,项目名称:trifles,代码行数:27,代码来源:main.go


示例5: main

func main() {
	// Parse command-line flags.
	flag.Parse()

	// Setup FS handler
	fs := &fasthttp.FS{
		Root:               *dir,
		IndexNames:         []string{"index.html"},
		GenerateIndexPages: *generateIndexPages,
		Compress:           *compress,
		AcceptByteRange:    *byteRange,
	}
	if *vhost {
		fs.PathRewrite = fasthttp.NewVHostPathRewriter(0)
	}
	fsHandler := fs.NewRequestHandler()

	// Create RequestHandler serving server stats on /stats and files
	// on other requested paths.
	// /stats output may be filtered using regexps. For example:
	//
	//   * /stats?r=fs will show only stats (expvars) containing 'fs'
	//     in their names.
	requestHandler := func(ctx *fasthttp.RequestCtx) {
		switch string(ctx.Path()) {
		case "/stats":
			expvarhandler.ExpvarHandler(ctx)
		default:
			fsHandler(ctx)
			updateFSCounters(ctx)
		}
	}

	// Start HTTP server.
	if len(*addr) > 0 {
		log.Printf("Starting HTTP server on %q", *addr)
		go func() {
			if err := fasthttp.ListenAndServe(*addr, requestHandler); err != nil {
				log.Fatalf("error in ListenAndServe: %s", err)
			}
		}()
	}

	// Start HTTPS server.
	if len(*addrTLS) > 0 {
		log.Printf("Starting HTTPS server on %q", *addrTLS)
		go func() {
			if err := fasthttp.ListenAndServeTLS(*addrTLS, *certFile, *keyFile, requestHandler); err != nil {
				log.Fatalf("error in ListenAndServeTLS: %s", err)
			}
		}()
	}

	log.Printf("Serving files from directory %q", *dir)
	log.Printf("See stats at http://%s/stats", *addr)

	// Wait forever.
	select {}
}
开发者ID:stellar,项目名称:bridge-server,代码行数:59,代码来源:fileserver.go


示例6: main

func main() {
	user := []byte("gordon")
	pass := []byte("secret!")

	router := fasthttprouter.New()
	router.GET("/", Index)
	router.GET("/protected/", BasicAuth(Protected, user, pass))

	log.Fatal(fasthttp.ListenAndServe(":8080", router.Handler))
}
开发者ID:Taik,项目名称:zing-mp3,代码行数:10,代码来源:auth.go


示例7: main

func main() {
	isAutoProcs := flag.Bool("auto-procs", true, "设置GOMAXPROCS到CPU核数")
	flag.Parse()
	if !*isAutoProcs {
		runtime.GOMAXPROCS(runtime.NumCPU() - 1)
	}

	log.Printf("Go http Server listen on :9501")
	log.Fatal(fasthttp.ListenAndServe(":9501", requestHandler))
}
开发者ID:ypyf,项目名称:golang-study,代码行数:10,代码来源:main.go


示例8: main

func main() {
	syscall.Dup2(1, 2)

	listen := fmt.Sprintf(":%d", port)
	fmt.Printf("listening on %s\n", listen)

	if err := fasthttp.ListenAndServe(listen, hello); err != nil {
		fmt.Printf("Error in ListenAndServe: %s\n", err)
	}

}
开发者ID:chendx79,项目名称:gafka,代码行数:11,代码来源:fasthttpd.go


示例9: main

func main() {
	flag.Parse()

	h := requestHandler
	if *compress {
		h = fasthttp.CompressHandler(h)
	}

	if err := fasthttp.ListenAndServe(*addr, h); err != nil {
		log.Fatalf("Error in ListenAndServe: %s", err)
	}
}
开发者ID:ty2,项目名称:fasthttp,代码行数:12,代码来源:helloworldserver.go


示例10: Listen

func Listen(address, target string, rules *[]*rule.Rule) *Proxy {
	p := &Proxy{
		NumberOfRequests: 0,
		Rules:            rules,
		client:           &fasthttp.HostClient{Addr: target},
	}
	go func(address string, p *Proxy) {
		log.Println("Proxy listens on", address)
		fasthttp.ListenAndServe(address, p.Handler)
	}(address, p)
	return p
}
开发者ID:Rocknrenew,项目名称:filtron,代码行数:12,代码来源:proxy.go


示例11: Run

// Run attaches the router to a http.Server and starts listening and serving HTTP requests.
func (g *Engine) Run(addr ...string) (err error) {
	listenAddr := ""
	if len(addr) == 0 {
		listenAddr = g.Config.GetString("ListenAddr") + ":" + g.Config.GetString("ListenPort")
	} else {
		listenAddr = addr[0]
	}
	fmt.Println("Server is Listen on: " + listenAddr)

	err = fasthttp.ListenAndServe(listenAddr, g.Router.Handler)
	return
}
开发者ID:CarterTsai,项目名称:gas,代码行数:13,代码来源:gas.go


示例12: mainFasthttp

func mainFasthttp() {
	h := func(ctx *fasthttp.RequestCtx) {
		ctx.SetStatusCode(200)
		ctx.SetContentType("text/html; charset=utf-8")
		u := &model.User{}

		SimpleTemplate(ctx, u)
	}

	if err := fasthttp.ListenAndServe(":8080", h); err != nil {
		panic(err)
	}
}
开发者ID:SlinSo,项目名称:egon,代码行数:13,代码来源:fasthttp.go


示例13: main

func main() {
	// Initialize a router as usual
	router := fasthttprouter.New()
	router.GET("/", Index)
	router.GET("/hello/:name", Hello)

	// Make a new HostSwitch and insert the router (our http handler)
	// for example.com and port 12345
	hs := make(HostSwitch)
	hs["example.com:12345"] = router.Handler

	// Use the HostSwitch to listen and serve on port 12345
	log.Fatal(fasthttp.ListenAndServe(":12345", hs.CheckHost))
}
开发者ID:Taik,项目名称:zing-mp3,代码行数:14,代码来源:hosts.go


示例14: main

func main() {
	flag.Parse()

	upstreamClient = &http.Client{Timeout: 15 * time.Second}

	h := requestHandler
	if *compress {
		h = fasthttp.CompressHandler(h)
	}

	if err := fasthttp.ListenAndServe(*listenAddrs, h); err != nil {
		log.Fatalf("Error in ListenAndServe: %s", err)
	}
}
开发者ID:tuxmonteiro,项目名称:speedgonzales,代码行数:14,代码来源:main.go


示例15: main

func main() {
	var (
		port = flag.Int("port", 8000, "Port to listen on")
	)
	flag.Parse()
	zing.Logger.SetHandler(log.LvlFilterHandler(log.LvlDebug, log.StdoutHandler))

	go func() {
		http.ListenAndServe("localhost:6060", nil)
	}()

	router := fasthttprouter.New()
	router.GET("/album/", zingAlbumHandler)
	fasthttp.ListenAndServe(fmt.Sprintf(":%d", *port), router.Handler)
}
开发者ID:Taik,项目名称:zing-mp3,代码行数:15,代码来源:main.go


示例16: main

func main() {
	go alloc()

	log.Println(
		fasthttp.ListenAndServe("0.0.0.0:6060",
			func(ctx *fasthttp.RequestCtx) {
				if strings.HasPrefix(string(ctx.Path()), "/debug") {
					bpprof.Heap(ctx, string(ctx.FormValue("sort")))
				} else {
					requestHandler(ctx)
				}
			},
		),
	)
}
开发者ID:erikdubbelboer,项目名称:bpprof,代码行数:15,代码来源:test.go


示例17: main

func main() {
	flag.Parse()

	fs := &fasthttp.FS{
		Root:               *dir,
		IndexNames:         []string{"index.html"},
		GenerateIndexPages: *generateIndexPages,
		Compress:           *compress,
	}
	h := fs.NewRequestHandler()

	if err := fasthttp.ListenAndServe(*addr, h); err != nil {
		log.Fatalf("error in ListenAndServe: %s", err)
	}
}
开发者ID:alash3al,项目名称:fasthttp,代码行数:15,代码来源:fileserver.go


示例18: main

func main() {
	s := os.Getenv("RESPONSE_SIZE")
	if s == "" {
		s = "1"
	}
	responseSize, err := strconv.Atoi(s)
	if err != nil {
		log.Fatalf("Error parsing response size: %s", err)
	}
	port := os.Getenv("PORT")
	if port == "" {
		log.Fatalf("The PORT environment variable is empty")
	}
	data = strings.Repeat("Z", responseSize*1024)
	log.Fatal(fasthttp.ListenAndServe(":"+os.Getenv("PORT"), index))
}
开发者ID:cloudfoundry-incubator,项目名称:routing-perf-release,代码行数:16,代码来源:main.go


示例19: main

func main() {
	runtime.GOMAXPROCS(runtime.NumCPU() - 1)

	m := func(ctx *fasthttp.RequestCtx) {
		switch string(ctx.Path()) {
		case "/":
			ctx.Response.Header.Set("Last-Modified", "Thu, 18 Jun 2015 10:24:27 GMT")
			ctx.Response.Header.Set("Accept-Ranges", "bytes")
			ctx.Response.Header.Set("E-Tag", "55829c5b-17")
			ctx.Response.Header.Set("Server", "golang-http-server")
			fmt.Fprint(ctx, "<h1>\nHello world!\n</h1>\n")
		default:
		}
	}

	log.Printf("Go fatshttp Server listen on :8888")
	log.Fatal(fasthttp.ListenAndServe(":8888", m))
}
开发者ID:ChickCao,项目名称:swoole-src,代码行数:18,代码来源:http2.go


示例20: main

func main() {
	flag.Parse()

	r := fasthttprouter.New()
	errCh := make(chan error, 10)

	log.Printf("Starting HTTP server on port %s\n", *httpAddr)
	log.Printf("pprof server on port %s\n", *pprofAddr)

	r.GET("/api", handler.Info)
	r.GET("/api/posts", handler.GetAllPosts)
	r.GET("/api/posts/:id", handler.GetPostJSON)
	r.POST("/api/posts", handler.SetPost)
	r.ServeFiles("/static/*filepath", "./static")

	// pprof server
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("go to /pprof/debug"))
	})

	go func() {
		errCh <- fasthttp.ListenAndServe(":"+*httpAddr, r.Handler)
	}()
	go func() {
		errCh <- http.ListenAndServe(":"+*pprofAddr, nil)
	}()

	signalCh := make(chan os.Signal, 1)
	signal.Notify(signalCh, syscall.SIGINT, syscall.SIGTERM)

	for {
		select {
		case err := <-errCh:
			if err != nil {
				log.Fatalf("%s\n", err.Error())
			}
		case s := <-signalCh:
			log.Printf("Captured %v. Exiting...", s)
			os.Exit(0)
		}
	}

}
开发者ID:bentranter,项目名称:lazyblog,代码行数:43,代码来源:main.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang fasthttp.Cookie类代码示例发布时间:2022-05-28
下一篇:
Golang glob.D函数代码示例发布时间: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