Files
pages/internal/server/domain_context.go
T
Anya Tokugawa c1175d389f Implement Knowledge City platform, organizer and DAV integration
Capture accumulated application, UI, CLI, regression tests and design documentation changes, including task project mapping and default CalDAV list naming.

Keep deployment data, backups, local credentials and build artifacts out of Git. Move the Compose enrollment token to an ignored local environment file.
2026-09-27 14:44:43 +09:00

122 lines
2.0 KiB
Go

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
}