本文整理汇总了Golang中github.com/valyala/fasthttp.ListenAndServe函数的典型用法代码示例。如果您正苦于以下问题:Golang ListenAndServe函数的具体用法?Golang ListenAndServe怎么用?Golang ListenAndServe使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ListenAndServe函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
}
示例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)
}
}
示例3: main
func main() {
router := fasthttprouter.New()
router.GET("/", Index)
router.GET("/hello/:name", Hello)
log.Fatal(fasthttp.ListenAndServe(":8080", router.Handler))
}
示例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)
}
}
示例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 {}
}
示例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))
}
示例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))
}
示例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)
}
}
示例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)
}
}
示例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
}
示例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
}
示例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)
}
}
示例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))
}
示例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)
}
}
示例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)
}