Skip to content

Commit

Permalink
improve variable naming
Browse files Browse the repository at this point in the history
  • Loading branch information
mpldr committed Feb 27, 2024
1 parent 209a477 commit 576cf4b
Show file tree
Hide file tree
Showing 6 changed files with 53 additions and 51 deletions.
6 changes: 3 additions & 3 deletions api/_routers/00-install-params.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@ var ServerNameRegex = regexp.MustCompile("[a-zA-Z0-9.:\\-_]+")

// var NumericIdRegex = regexp.MustCompile("[0-9]+")
func GetParam(name string, r *http.Request) string {
p := httprouter.ParamsFromContext(r.Context())
if p == nil {
parameter := httprouter.ParamsFromContext(r.Context())
if parameter == nil {
return ""
}
return p.ByName(name)
return parameter.ByName(name)
}

func ForceSetParam(name string, val string, r *http.Request) *http.Request {
Expand Down
28 changes: 14 additions & 14 deletions api/_routers/01-install_metadata.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ func NewInstallMetadataRouter(ignoreHost bool, actionName string, counter *Reque
}
}

func (i *InstallMetadataRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
requestId := i.counter.NextId()
func (router *InstallMetadataRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
requestId := router.counter.NextId()
logger := logrus.WithFields(logrus.Fields{
"method": r.Method,
"host": r.Host,
Expand All @@ -54,44 +54,44 @@ func (i *InstallMetadataRouter) ServeHTTP(w http.ResponseWriter, r *http.Request
ctx := r.Context()
ctx = context.WithValue(ctx, common.ContextRequestStartTime, util.NowMillis())
ctx = context.WithValue(ctx, common.ContextRequestId, requestId)
ctx = context.WithValue(ctx, common.ContextAction, i.actionName)
ctx = context.WithValue(ctx, common.ContextIgnoreHost, i.ignoreHost)
ctx = context.WithValue(ctx, common.ContextAction, router.actionName)
ctx = context.WithValue(ctx, common.ContextIgnoreHost, router.ignoreHost)
ctx = context.WithValue(ctx, common.ContextLogger, logger)
r = r.WithContext(ctx)

if i.next != nil {
i.next.ServeHTTP(w, r)
if router.next != nil {
router.next.ServeHTTP(w, r)
}
}

func GetActionName(r *http.Request) string {
x, ok := r.Context().Value(common.ContextAction).(string)
action, ok := r.Context().Value(common.ContextAction).(string)
if !ok {
return "<UNKNOWN>"
}
return x
return action
}

func ShouldIgnoreHost(r *http.Request) bool {
x, ok := r.Context().Value(common.ContextIgnoreHost).(bool)
ignoreHost, ok := r.Context().Value(common.ContextIgnoreHost).(bool)
if !ok {
return false
}
return x
return ignoreHost
}

func GetLogger(r *http.Request) *logrus.Entry {
x, ok := r.Context().Value(common.ContextLogger).(*logrus.Entry)
log, ok := r.Context().Value(common.ContextLogger).(*logrus.Entry)
if !ok {
return nil
}
return x
return log
}

func GetRequestDuration(r *http.Request) float64 {
x, ok := r.Context().Value(common.ContextRequestStartTime).(int64)
duration, ok := r.Context().Value(common.ContextRequestStartTime).(int64)
if !ok {
return -1
}
return float64(util.NowMillis()-x) / 1000.0
return float64(util.NowMillis()-duration) / 1000.0
}
12 changes: 6 additions & 6 deletions api/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,23 +29,23 @@ func buildPrimaryRouter() *httprouter.Router {
func methodNotAllowedFn(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusMethodNotAllowed)
b, err := json.Marshal(_responses.MethodNotAllowed())
reponse, err := json.Marshal(_responses.MethodNotAllowed())
if err != nil {
sentry.CaptureException(fmt.Errorf("error preparing MethodNotAllowed: %v", err))
return
}
w.Write(b)
w.Write(reponse)
}

func notFoundFn(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusNotFound)
b, err := json.Marshal(_responses.NotFoundError())
reponse, err := json.Marshal(_responses.NotFoundError())
if err != nil {
sentry.CaptureException(fmt.Errorf("error preparing NotFound: %v", err))
return
}
w.Write(b)
w.Write(reponse)
}

func finishCorsFn(w http.ResponseWriter, r *http.Request) {
Expand All @@ -65,10 +65,10 @@ func panicFn(w http.ResponseWriter, r *http.Request, i interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)

b, err := json.Marshal(_responses.InternalServerError(errors.New("unexpected error")))
reponse, err := json.Marshal(_responses.InternalServerError(errors.New("unexpected error")))
if err != nil {
sentry.CaptureException(fmt.Errorf("error preparing InternalServerError: %v", err))
return
}
w.Write(b)
w.Write(reponse)
}
12 changes: 7 additions & 5 deletions api/webserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,11 @@ import (
"github.com/t2bot/matrix-media-repo/common/config"
)

var srv *http.Server
var waitGroup = &sync.WaitGroup{}
var reload = false
var (
srv *http.Server
waitGroup = &sync.WaitGroup{}
reload = false
)

func Init() *sync.WaitGroup {
address := net.JoinHostPort(config.Get().General.BindAddress, strconv.Itoa(config.Get().General.Port))
Expand All @@ -35,8 +37,8 @@ func Init() *sync.WaitGroup {
limiter.SetBurst(config.Get().RateLimit.BurstCount)
limiter.SetMax(config.Get().RateLimit.RequestsPerSecond)

b, _ := json.Marshal(_responses.RateLimitReached())
limiter.SetMessage(string(b))
reponse, _ := json.Marshal(_responses.RateLimitReached())
limiter.SetMessage(string(reponse))
limiter.SetMessageContentType("application/json")

handler = tollbooth.LimitHandler(limiter, handler)
Expand Down
12 changes: 6 additions & 6 deletions database/table_url_previews.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,8 @@ func (s *urlPreviewsTableStatements) Prepare(ctx rcontext.RequestContext) *urlPr
}
}

func (s *urlPreviewsTableWithContext) Get(url string, ts int64, languageHeader string) (*DbUrlPreview, error) {
row := s.statements.selectUrlPreview.QueryRowContext(s.ctx, url, ts, languageHeader)
func (s *urlPreviewsTableWithContext) Get(url string, timestamp int64, languageHeader string) (*DbUrlPreview, error) {
row := s.statements.selectUrlPreview.QueryRowContext(s.ctx, url, timestamp, languageHeader)
val := &DbUrlPreview{}
err := row.Scan(&val.Url, &val.ErrorCode, &val.BucketTs, &val.SiteUrl, &val.SiteName, &val.ResourceType, &val.Description, &val.Title, &val.ImageMxc, &val.ImageType, &val.ImageSize, &val.ImageWidth, &val.ImageHeight, &val.LanguageHeader)
if errors.Is(err, sql.ErrNoRows) {
Expand All @@ -75,8 +75,8 @@ func (s *urlPreviewsTableWithContext) Get(url string, ts int64, languageHeader s
return val, err
}

func (s *urlPreviewsTableWithContext) Insert(p *DbUrlPreview) error {
_, err := s.statements.insertUrlPreview.ExecContext(s.ctx, p.Url, p.ErrorCode, p.BucketTs, p.SiteUrl, p.SiteName, p.ResourceType, p.Description, p.Title, p.ImageMxc, p.ImageType, p.ImageSize, p.ImageWidth, p.ImageHeight, p.LanguageHeader)
func (s *urlPreviewsTableWithContext) Insert(preview *DbUrlPreview) error {
_, err := s.statements.insertUrlPreview.ExecContext(s.ctx, preview.Url, preview.ErrorCode, preview.BucketTs, preview.SiteUrl, preview.SiteName, preview.ResourceType, preview.Description, preview.Title, preview.ImageMxc, preview.ImageType, preview.ImageSize, preview.ImageWidth, preview.ImageHeight, preview.LanguageHeader)
return err
}

Expand All @@ -89,7 +89,7 @@ func (s *urlPreviewsTableWithContext) InsertError(url string, errorCode string)
})
}

func (s *urlPreviewsTableWithContext) DeleteOlderThan(ts int64) error {
_, err := s.statements.deleteOldUrlPreviews.ExecContext(s.ctx, ts)
func (s *urlPreviewsTableWithContext) DeleteOlderThan(timestamp int64) error {
_, err := s.statements.deleteOldUrlPreviews.ExecContext(s.ctx, timestamp)
return err
}
34 changes: 17 additions & 17 deletions matrix/server_discovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,11 @@ func GetServerApiUrl(hostname string) (string, string, error) {
}

addrErr := &net.AddrError{}
h, p, err := net.SplitHostPort(hostname)
host, port, err := net.SplitHostPort(hostname)
defPort := false
switch {
case errors.As(err, &addrErr) && addrErr.Err == "missing port in address":
h, p, err = net.SplitHostPort(hostname + ":8448")
host, port, err = net.SplitHostPort(hostname + ":8448")
if err != nil {
return "", "", fmt.Errorf("failed to parse hostname: %w", err)
}
Expand All @@ -62,9 +62,9 @@ func GetServerApiUrl(hostname string) (string, string, error) {
}

// Step 1 of the discovery process: if the hostname is an IP, use that with explicit or default port
logrus.Debug("Testing if " + h + " is an IP address")
if is.IP(h) {
url := fmt.Sprintf("https://%s", net.JoinHostPort(h, p))
logrus.Debug("Testing if " + host + " is an IP address")
if is.IP(host) {
url := fmt.Sprintf("https://%s", net.JoinHostPort(host, port))
server := cachedServer{url, hostname}
apiUrlCacheInstance.Set(hostname, server, cache.DefaultExpiration)
logrus.Debug("Server API URL for " + hostname + " is " + url + " (IP address)")
Expand All @@ -74,17 +74,17 @@ func GetServerApiUrl(hostname string) (string, string, error) {
// Step 2: if the hostname is not an IP address, and an explicit port is given, use that
logrus.Debug("Testing if a default port was used. Using default = ", defPort)
if !defPort {
url := fmt.Sprintf("https://%s", net.JoinHostPort(h, p))
server := cachedServer{url, h}
url := fmt.Sprintf("https://%s", net.JoinHostPort(host, port))
server := cachedServer{url, host}
apiUrlCacheInstance.Set(hostname, server, cache.DefaultExpiration)
logrus.Debugf("Server API URL for %s is %s (explicit port)", hostname, url)
return url, h, nil
return url, host, nil
}

// Step 3: if the hostname is not an IP address and no explicit port is given, do .well-known
// Note that we have sprawling branches here because we need to fall through to step 4 if parsing fails
logrus.Debug("Doing .well-known lookup on " + h)
r, err := http.Get(fmt.Sprintf("https://%s/.well-known/matrix/server", h))
logrus.Debug("Doing .well-known lookup on " + host)
r, err := http.Get(fmt.Sprintf("https://%s/.well-known/matrix/server", host))
if r != nil {
defer r.Body.Close()
}
Expand Down Expand Up @@ -183,10 +183,10 @@ func GetServerApiUrl(hostname string) (string, string, error) {
realAddr = realAddr[0 : len(realAddr)-1]
}
url := fmt.Sprintf("https://%s", net.JoinHostPort(realAddr, strconv.Itoa(int(addrs[0].Port))))
server := cachedServer{url, h}
server := cachedServer{url, host}
apiUrlCacheInstance.Set(hostname, server, cache.DefaultExpiration)
logrus.Debugf("Server API URL for %s is %s (SRV)", hostname, url)
return url, h, nil
return url, host, nil
}

// Step 5: try resolving a hostname using DEPRECATED SRV records and use it
Expand All @@ -200,17 +200,17 @@ func GetServerApiUrl(hostname string) (string, string, error) {
realAddr = realAddr[0 : len(realAddr)-1]
}
url := fmt.Sprintf("https://%s", net.JoinHostPort(realAddr, strconv.Itoa(int(addrs[0].Port))))
server := cachedServer{url, h}
server := cachedServer{url, host}
apiUrlCacheInstance.Set(hostname, server, cache.DefaultExpiration)
logrus.Debugf("Server API URL for %s is %s (SRV-Deprecated)", hostname, url)
return url, h, nil
return url, host, nil
}

// Step 6: use the target host as-is
logrus.Debug("Using host as-is: ", hostname)
url := fmt.Sprintf("https://%s", net.JoinHostPort(h, p))
server := cachedServer{url, h}
url := fmt.Sprintf("https://%s", net.JoinHostPort(host, port))
server := cachedServer{url, host}
apiUrlCacheInstance.Set(hostname, server, cache.DefaultExpiration)
logrus.Debugf("Server API URL for %s is %s (fallback)", hostname, url)
return url, h, nil
return url, host, nil
}

0 comments on commit 576cf4b

Please sign in to comment.