helloworldserver.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "log"
  6. "github.com/valyala/fasthttp"
  7. )
  8. var (
  9. addr = flag.String("addr", ":8080", "TCP address to listen to")
  10. compress = flag.Bool("compress", false, "Whether to enable transparent response compression")
  11. )
  12. func main() {
  13. flag.Parse()
  14. h := requestHandler
  15. if *compress {
  16. h = fasthttp.CompressHandler(h)
  17. }
  18. if err := fasthttp.ListenAndServe(*addr, h); err != nil {
  19. log.Fatalf("Error in ListenAndServe: %v", err)
  20. }
  21. }
  22. func requestHandler(ctx *fasthttp.RequestCtx) {
  23. fmt.Fprintf(ctx, "Hello, world!\n\n")
  24. fmt.Fprintf(ctx, "Request method is %q\n", ctx.Method())
  25. fmt.Fprintf(ctx, "RequestURI is %q\n", ctx.RequestURI())
  26. fmt.Fprintf(ctx, "Requested path is %q\n", ctx.Path())
  27. fmt.Fprintf(ctx, "Host is %q\n", ctx.Host())
  28. fmt.Fprintf(ctx, "Query string is %q\n", ctx.QueryArgs())
  29. fmt.Fprintf(ctx, "User-Agent is %q\n", ctx.UserAgent())
  30. fmt.Fprintf(ctx, "Connection has been established at %s\n", ctx.ConnTime())
  31. fmt.Fprintf(ctx, "Request has been started at %s\n", ctx.Time())
  32. fmt.Fprintf(ctx, "Serial request number for the current connection is %d\n", ctx.ConnRequestNum())
  33. fmt.Fprintf(ctx, "Your ip is %q\n\n", ctx.RemoteIP())
  34. fmt.Fprintf(ctx, "Raw request is:\n---CUT---\n%s\n---CUT---", &ctx.Request)
  35. ctx.SetContentType("text/plain; charset=utf8")
  36. // Set arbitrary headers
  37. ctx.Response.Header.Set("X-My-Header", "my-header-value")
  38. // Set cookies
  39. var c fasthttp.Cookie
  40. c.SetKey("cookie-name")
  41. c.SetValue("cookie-value")
  42. ctx.Response.Header.SetCookie(&c)
  43. }