server.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. func InitServer() error {
  15. m := autocert.Manager{
  16. Cache: autocert.DirCache(*STORAGE),
  17. Prompt: autocert.AcceptTOS,
  18. HostPolicy: func(ctx context.Context, host string) error {
  19. if _, ok := HOSTS[host]; ok {
  20. return nil
  21. }
  22. return errors.New("Unkown host(" + host + ")")
  23. },
  24. }
  25. s := &http.Server{
  26. Addr: ":https",
  27. TLSConfig: &tls.Config{GetCertificate: m.GetCertificate},
  28. Handler: ServeHTTP(),
  29. }
  30. return s.ListenAndServeTLS("", "")
  31. }
  32. func ServeHTTP() http.Handler {
  33. return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
  34. if upstreams, ok := HOSTS[req.Host]; ok {
  35. forwarder, _ := forward.New()
  36. loadbalancer, _ := roundrobin.New(forwarder)
  37. for _, upstream := range upstreams {
  38. loadbalancer.UpsertServer(testutils.ParseURI(upstream))
  39. }
  40. loadbalancer.ServeHTTP(res, req)
  41. }
  42. http.Error(res, "The request domain couldn't be found here", http.StatusNotImplemented)
  43. })
  44. }