server.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package main
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "errors"
  6. "net/http"
  7. )
  8. import (
  9. "github.com/vulcand/oxy/forward"
  10. "github.com/vulcand/oxy/roundrobin"
  11. "github.com/vulcand/oxy/testutils"
  12. "golang.org/x/crypto/acme/autocert"
  13. )
  14. // Initialize the autocert manager and configure it,
  15. // also create an instance of the http.Server and link the autocert manager to it.
  16. func InitServer() error {
  17. m := autocert.Manager{
  18. Cache: autocert.DirCache(*STORAGE),
  19. Prompt: autocert.AcceptTOS,
  20. HostPolicy: func(ctx context.Context, host string) error {
  21. if _, ok := HOSTS[host]; ok {
  22. return nil
  23. }
  24. return errors.New("Unkown host(" + host + ")")
  25. },
  26. }
  27. s := &http.Server{
  28. Addr: *HTTPS_ADDR,
  29. TLSConfig: &tls.Config{GetCertificate: m.GetCertificate},
  30. Handler: ServeHTTP(),
  31. }
  32. return s.ListenAndServeTLS("", "")
  33. }
  34. // The main server handler
  35. func ServeHTTP() http.Handler {
  36. return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
  37. if upstreams, ok := HOSTS[req.Host]; ok {
  38. forwarder, _ := forward.New()
  39. loadbalancer, _ := roundrobin.New(forwarder)
  40. for _, upstream := range upstreams {
  41. loadbalancer.UpsertServer(testutils.ParseURI(upstream))
  42. }
  43. loadbalancer.ServeHTTP(res, req)
  44. }
  45. http.Error(res, "The request domain couldn't be found here", http.StatusNotImplemented)
  46. })
  47. }