multidomain.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package main
  2. import (
  3. "fmt"
  4. "github.com/valyala/fasthttp"
  5. )
  6. var domains = make(map[string]fasthttp.RequestHandler)
  7. func main() {
  8. server := &fasthttp.Server{
  9. // You can check the access using openssl command:
  10. // $ openssl s_client -connect localhost:8080 << EOF
  11. // > GET /
  12. // > Host: localhost
  13. // > EOF
  14. //
  15. // $ openssl s_client -connect localhost:8080 << EOF
  16. // > GET /
  17. // > Host: 127.0.0.1:8080
  18. // > EOF
  19. //
  20. Handler: func(ctx *fasthttp.RequestCtx) {
  21. h, ok := domains[string(ctx.Host())]
  22. if !ok {
  23. ctx.NotFound()
  24. return
  25. }
  26. h(ctx)
  27. },
  28. }
  29. // preparing first host
  30. cert, priv, err := fasthttp.GenerateTestCertificate("localhost:8080")
  31. if err != nil {
  32. panic(err)
  33. }
  34. domains["localhost:8080"] = func(ctx *fasthttp.RequestCtx) {
  35. ctx.WriteString("You are accessing to localhost:8080\n")
  36. }
  37. err = server.AppendCertEmbed(cert, priv)
  38. if err != nil {
  39. panic(err)
  40. }
  41. // preparing second host
  42. cert, priv, err = fasthttp.GenerateTestCertificate("127.0.0.1")
  43. if err != nil {
  44. panic(err)
  45. }
  46. domains["127.0.0.1:8080"] = func(ctx *fasthttp.RequestCtx) {
  47. ctx.WriteString("You are accessing to 127.0.0.1:8080\n")
  48. }
  49. err = server.AppendCertEmbed(cert, priv)
  50. if err != nil {
  51. panic(err)
  52. }
  53. fmt.Println(server.ListenAndServeTLS(":8080", "", ""))
  54. }