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)
	}
}
Exemplo n.º 2
0
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)
}
Exemplo n.º 3
0
func main() {
	router := fasthttprouter.New()
	router.GET("/", Index)
	router.GET("/hello/:name", Hello)

	log.Fatal(fasthttp.ListenAndServe(":8080", router.Handler))
}
Exemplo n.º 4
0
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)
	}
}
Exemplo n.º 5
0
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 {}
}
Exemplo n.º 6
0
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))
}
Exemplo n.º 7
0
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))
}
Exemplo n.º 8
0
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)
	}

}
Exemplo n.º 9
0
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)
	}
}
Exemplo n.º 10
0
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
}
Exemplo n.º 11
0
// 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
}
Exemplo n.º 12
0
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)
	}
}
Exemplo n.º 13
0
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))
}
Exemplo n.º 14
0
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)
	}
}
Exemplo n.º 15
0
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)
}
Exemplo n.º 16
0
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)
				}
			},
		),
	)
}
Exemplo n.º 17
0
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)
	}
}
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))
}
Exemplo n.º 19
0
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))
}
Exemplo n.º 20
0
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)
		}
	}

}
Exemplo n.º 21
0
func main() {
	// The server will listen for incoming requests on this address.
	listenAddr := "127.0.0.1:8181"

	// This function will be called by the server for each incoming request.
	//
	// RequestCtx provides a lot of functionality related to http request
	// processing. See RequestCtx docs for details.
	requestHandler := func(ctx *fasthttp.RequestCtx) {
		fmt.Fprintf(ctx, "Hello, world!")
	}

	// Start the server with default settings.
	// Create Server instance for adjusting server settings.
	//
	// ListenAndServe returns only on error, so usually it blocks forever.
	if err := fasthttp.ListenAndServe(listenAddr, requestHandler); err != nil {
		log.Fatalf("error in ListenAndServe: %s", err)
	}
}
Exemplo n.º 22
0
func ExampleFS() {
	fs := &fasthttp.FS{
		// Path to directory to serve.
		Root: "/var/www/static-site",

		// Generate index pages if client requests directory contents.
		GenerateIndexPages: true,

		// Enable transparent compression to save network traffic.
		Compress: true,
	}

	// Create request handler for serving static files.
	h := fs.NewRequestHandler()

	// Start the server.
	if err := fasthttp.ListenAndServe(":8080", h); err != nil {
		log.Fatalf("error in ListenAndServe: %s", err)
	}
}
Exemplo n.º 23
0
func ExampleRequestCtx_Logger() {
	requestHandler := func(ctx *fasthttp.RequestCtx) {
		if string(ctx.Path()) == "/top-secret" {
			ctx.Logger().Printf("Alarm! Alien intrusion detected!")
			ctx.Error("Access denied!", fasthttp.StatusForbidden)
			return
		}

		// Logger may be cached in local variables.
		logger := ctx.Logger()

		logger.Printf("Good request from User-Agent %q", ctx.Request.Header.UserAgent())
		fmt.Fprintf(ctx, "Good request to %q", ctx.Path())
		logger.Printf("Multiple log messages may be written during a single request")
	}

	if err := fasthttp.ListenAndServe(":80", requestHandler); err != nil {
		log.Fatalf("error in ListenAndServe: %s", err)
	}
}
func ExampleByteBuffer() {
	// This request handler sets 'Your-IP' response header
	// to 'Your IP is <ip>'. It uses ByteBuffer for constructing response
	// header value with zero memory allocations.
	yourIPRequestHandler := func(ctx *fasthttp.RequestCtx) {
		b := fasthttp.AcquireByteBuffer()
		b.B = append(b.B, "Your IP is <"...)
		b.B = fasthttp.AppendIPv4(b.B, ctx.RemoteIP())
		b.B = append(b.B, ">"...)
		ctx.Response.Header.SetBytesV("Your-IP", b.B)

		fmt.Fprintf(ctx, "Check response headers - they must contain 'Your-IP: %s'", b.B)

		// It is safe to release byte buffer now, since it is
		// no longer used.
		fasthttp.ReleaseByteBuffer(b)
	}

	// Start fasthttp server returning your ip in response headers.
	fasthttp.ListenAndServe(":8080", yourIPRequestHandler)
}
Exemplo n.º 25
0
func main() {
	flag.Parse()

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

	// Start HTTP server.
	if len(*addr) > 0 {
		log.Printf("Starting HTTP server on %q", *addr)
		go func() {
			if err := fasthttp.ListenAndServe(*addr, h); 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, h); err != nil {
				log.Fatalf("error in ListenAndServeTLS: %s", err)
			}
		}()
	}

	log.Printf("Serving files from directory %q", *dir)

	// Wait forever.
	select {}
}
Exemplo n.º 26
0
func main() {
	// 创建基于redis的oauth2管理实例
	manager := manage.NewRedisManager(
		&token.RedisConfig{Addr: "192.168.33.70:6379"},
	)
	// 使用临时客户端存储
	manager.MapClientStorage(client.NewTempStore(&models.Client{
		ID:     "222222",
		Secret: "22222222",
		Domain: "http://localhost:9094",
	}))

	srv := server.NewFastServer(server.NewConfig(), manager)

	log.Println("OAuth2 server is running at 9096 port.")
	fasthttp.ListenAndServe(":9096", func(ctx *fasthttp.RequestCtx) {
		switch string(ctx.Request.URI().Path()) {
		case "/authorize":
			authReq, err := srv.GetAuthorizeRequest(ctx)
			if err != nil {
				ctx.Error(err.Error(), 400)
				return
			}
			authReq.UserID = "000000"
			// TODO: 登录验证、授权处理
			err = srv.HandleAuthorizeRequest(ctx, authReq)
			if err != nil {
				ctx.Error(err.Error(), 400)
			}
		case "/token":
			err := srv.HandleTokenRequest(ctx)
			if err != nil {
				ctx.Error(err.Error(), 400)
			}
		}
	})
}
Exemplo n.º 27
0
func ExampleRequestCtx_Hijack() {
	// hijackHandler is called on hijacked connection.
	hijackHandler := func(c net.Conn) {
		fmt.Fprintf(c, "This message is sent over a hijacked connection to the client %s\n", c.RemoteAddr())
		fmt.Fprintf(c, "Send me something and I'll echo it to you\n")
		var buf [1]byte
		for {
			if _, err := c.Read(buf[:]); err != nil {
				log.Printf("error when reading from hijacked connection: %s", err)
				return
			}
			fmt.Fprintf(c, "You sent me %q. Waiting for new data\n", buf[:])
		}
	}

	// requestHandler is called for each incoming request.
	requestHandler := func(ctx *fasthttp.RequestCtx) {
		path := ctx.Path()
		switch {
		case string(path) == "/hijack":
			// Note that the connection is hijacked only after
			// returning from requestHandler and sending http response.
			ctx.Hijack(hijackHandler)

			// The connection will be hijacked after sending this response.
			fmt.Fprintf(ctx, "Hijacked the connection!")
		case string(path) == "/":
			fmt.Fprintf(ctx, "Root directory requested")
		default:
			fmt.Fprintf(ctx, "Requested path is %q", path)
		}
	}

	if err := fasthttp.ListenAndServe(":80", requestHandler); err != nil {
		log.Fatalf("error in ListenAndServe: %s", err)
	}
}
func ExampleRequestCtx_SetBodyStreamWriter() {
	// Start fasthttp server for streaming responses.
	if err := fasthttp.ListenAndServe(":8080", responseStreamHandler); err != nil {
		log.Fatalf("unexpected error in server: %s", err)
	}
}
Exemplo n.º 29
0
func Listen(address, ruleFile string, p *proxy.Proxy) {
	log.Println("API listens on", address)
	a := &API{p, ruleFile}
	fasthttp.ListenAndServe(address, a.Handler)
}
Exemplo n.º 30
0
func startFastHttpRouting() {
	mux := routing.New()
	mux.Get("/hello", fastHttpRoutingHandler)
	fasthttp.ListenAndServe(":"+strconv.Itoa(port), mux.HandleRequest)
}