forked from tangled.org/core
Monorepo for Tangled — https://tangled.org
1package middleware 2 3import ( 4 "net/http" 5 "strings" 6 7 "github.com/go-chi/chi/v5" 8 "tangled.org/core/appview/state/userutil" 9) 10 11func Normalize() middlewareFunc { 12 return func(next http.Handler) http.Handler { 13 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 14 pat := chi.URLParam(r, "*") 15 pathParts := strings.SplitN(pat, "/", 2) 16 if len(pathParts) == 0 { 17 next.ServeHTTP(w, r) 18 return 19 } 20 21 firstPart := pathParts[0] 22 23 // if using a flattened DID (like you would in go modules), unflatten 24 if userutil.IsFlattenedDid(firstPart) { 25 unflattenedDid := userutil.UnflattenDid(firstPart) 26 redirectPath := strings.Join(append([]string{unflattenedDid}, pathParts[1:]...), "/") 27 28 redirectURL := *r.URL 29 redirectURL.Path = "/" + redirectPath 30 31 http.Redirect(w, r, redirectURL.String(), http.StatusFound) 32 return 33 } 34 35 // if using a handle with @, rewrite to work without @ 36 if normalized := strings.TrimPrefix(firstPart, "@"); userutil.IsHandle(normalized) { 37 redirectPath := strings.Join(append([]string{normalized}, pathParts[1:]...), "/") 38 39 redirectURL := *r.URL 40 redirectURL.Path = "/" + redirectPath 41 42 http.Redirect(w, r, redirectURL.String(), http.StatusFound) 43 return 44 } 45 46 next.ServeHTTP(w, r) 47 return 48 }) 49 } 50}