package server import ( "context" "log" "net/http" "sync" "pageswiki/internal/store" ) type requestDomainKey struct{} type requestDomainLookup struct { once sync.Once host string domain *store.Domain err error } func cacheRequestDomain(r *http.Request) *http.Request { return r.WithContext(context.WithValue(r.Context(), requestDomainKey{}, &requestDomainLookup{host: r.Host})) } func (s *Server) currentDomain() *store.Domain { sp, err := s.store.GetDefaultDomain() if err != nil { return &store.Domain{ ID: 1, Name: "default", Title: "Default Domain", Enabled: true, } } return sp } func (s *Server) currentCampus() *store.Campus { campus, err := s.store.GetDefaultCampus() if err != nil { return &store.Campus{ ID: 1, Name: "default", Title: "Default Campus", DefaultLang: "en", Enabled: true, } } return campus } func (s *Server) campusForDomain( domain *store.Domain, ) *store.Campus { if domain == nil { return s.currentCampus() } campus, err := s.store.GetCampusByUUID( domain.CampusUUID, ) if err != nil { return s.currentCampus() } return campus } func (s *Server) domainForRequest( r *http.Request, ) *store.Domain { domain, _ := s.domainForRequestWithError(r) return domain } func (s *Server) domainForRequestWithError( r *http.Request, ) (*store.Domain, error) { if r == nil { return s.currentDomain(), nil } if cached, ok := r.Context().Value(requestDomainKey{}).(*requestDomainLookup); ok && cached.host == r.Host { cached.once.Do(func() { cached.domain, cached.err = s.store.GetDomainByHost(r.Host) }) return cached.domain, cached.err } sp, err := s.store.GetDomainByHost( r.Host, ) if err != nil { return nil, err } return sp, nil } func logDomainLookupError(r *http.Request, err error) { log.Printf( "domain lookup failed host=%q: %v", r.Host, err, ) } func (s *Server) domainUUIDForRequest(r *http.Request) string { domain := s.domainForRequest(r) if domain == nil { return "" } return domain.UUID }