all: use strs.CutPrefix and strs.CutSuffix more

Updates places where we use HasPrefix + TrimPrefix to use the combined
function.

Updates #5309

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
This commit is contained in:
Mihai Parparita
2022-11-18 10:13:14 -08:00
committed by Mihai Parparita
parent 41e1d336cc
commit 33520920c3
14 changed files with 46 additions and 34 deletions

View File

@@ -166,13 +166,13 @@ func (s *peerAPIServer) hasFilesWaiting() bool {
if strings.HasSuffix(name, partialSuffix) {
continue
}
if strings.HasSuffix(name, deletedSuffix) { // for Windows + tests
if name, ok := strs.CutSuffix(name, deletedSuffix); ok { // for Windows + tests
// After we're done looping over files, then try
// to delete this file. Don't do it proactively,
// as the OS may return "foo.jpg.deleted" before "foo.jpg"
// and we don't want to delete the ".deleted" file before
// enumerating to the "foo.jpg" file.
defer tryDeleteAgain(filepath.Join(s.rootDir, strings.TrimSuffix(name, deletedSuffix)))
defer tryDeleteAgain(filepath.Join(s.rootDir, name))
continue
}
if de.Type().IsRegular() {
@@ -225,11 +225,11 @@ func (s *peerAPIServer) WaitingFiles() (ret []apitype.WaitingFile, err error) {
if strings.HasSuffix(name, partialSuffix) {
continue
}
if strings.HasSuffix(name, deletedSuffix) { // for Windows + tests
if name, ok := strs.CutSuffix(name, deletedSuffix); ok { // for Windows + tests
if deleted == nil {
deleted = map[string]bool{}
}
deleted[strings.TrimSuffix(name, deletedSuffix)] = true
deleted[name] = true
continue
}
if de.Type().IsRegular() {

View File

@@ -670,7 +670,11 @@ func (h *Handler) serveFiles(w http.ResponseWriter, r *http.Request) {
http.Error(w, "file access denied", http.StatusForbidden)
return
}
suffix := strings.TrimPrefix(r.URL.EscapedPath(), "/localapi/v0/files/")
suffix, ok := strs.CutPrefix(r.URL.EscapedPath(), "/localapi/v0/files/")
if !ok {
http.Error(w, "misconfigured", http.StatusInternalServerError)
return
}
if suffix == "" {
if r.Method != "GET" {
http.Error(w, "want GET to list files", 400)
@@ -774,7 +778,11 @@ func (h *Handler) serveFilePut(w http.ResponseWriter, r *http.Request) {
return
}
upath := strings.TrimPrefix(r.URL.EscapedPath(), "/localapi/v0/file-put/")
upath, ok := strs.CutPrefix(r.URL.EscapedPath(), "/localapi/v0/file-put/")
if !ok {
http.Error(w, "misconfigured", http.StatusInternalServerError)
return
}
stableIDStr, filenameEscaped, ok := strings.Cut(upath, "/")
if !ok {
http.Error(w, "bogus URL", 400)
@@ -1159,7 +1167,8 @@ func (h *Handler) serveProfiles(w http.ResponseWriter, r *http.Request) {
}
suffix, ok := strs.CutPrefix(r.URL.EscapedPath(), "/localapi/v0/profiles/")
if !ok {
panic("misconfigured")
http.Error(w, "misconfigured", http.StatusInternalServerError)
return
}
if suffix == "" {
switch r.Method {