Skip to content

Commit d0a8a0d

Browse files
committed
Use strings.Cut in a few places
Now that we're 1.20+ instead of 1.14+ we can use 1.18's strings.Cut in a few places to simplify code.
1 parent 71307f9 commit d0a8a0d

File tree

4 files changed

+6
-21
lines changed

4 files changed

+6
-21
lines changed

Diff for: middleware/compress.go

+2-5
Original file line numberDiff line numberDiff line change
@@ -277,16 +277,13 @@ type compressResponseWriter struct {
277277
func (cw *compressResponseWriter) isCompressible() bool {
278278
// Parse the first part of the Content-Type response header.
279279
contentType := cw.Header().Get("Content-Type")
280-
if idx := strings.Index(contentType, ";"); idx >= 0 {
281-
contentType = contentType[0:idx]
282-
}
280+
contentType, _, _ = strings.Cut(contentType, ";")
283281

284282
// Is the content type compressible?
285283
if _, ok := cw.contentTypes[contentType]; ok {
286284
return true
287285
}
288-
if idx := strings.Index(contentType, "/"); idx > 0 {
289-
contentType = contentType[0:idx]
286+
if contentType, _, hadSlash := strings.Cut(contentType, "/"); hadSlash {
290287
_, ok := cw.contentWildcards[contentType]
291288
return ok
292289
}

Diff for: middleware/realip.go

+1-5
Original file line numberDiff line numberDiff line change
@@ -47,11 +47,7 @@ func realIP(r *http.Request) string {
4747
} else if xrip := r.Header.Get(xRealIP); xrip != "" {
4848
ip = xrip
4949
} else if xff := r.Header.Get(xForwardedFor); xff != "" {
50-
i := strings.Index(xff, ",")
51-
if i == -1 {
52-
i = len(xff)
53-
}
54-
ip = xff[:i]
50+
ip, _, _ = strings.Cut(xff, ",")
5551
}
5652
if ip == "" || net.ParseIP(ip) == nil {
5753
return ""

Diff for: middleware/route_headers.go

+1-7
Original file line numberDiff line numberDiff line change
@@ -133,13 +133,7 @@ type Pattern struct {
133133

134134
func NewPattern(value string) Pattern {
135135
p := Pattern{}
136-
if i := strings.IndexByte(value, '*'); i >= 0 {
137-
p.wildcard = true
138-
p.prefix = value[0:i]
139-
p.suffix = value[i+1:]
140-
} else {
141-
p.prefix = value
142-
}
136+
p.prefix, p.suffix, p.wildcard = strings.Cut(value, "*")
143137
return p
144138
}
145139

Diff for: tree.go

+2-4
Original file line numberDiff line numberDiff line change
@@ -730,11 +730,9 @@ func patNextSegment(pattern string) (nodeTyp, string, string, byte, int, int) {
730730
tail = pattern[pe]
731731
}
732732

733-
var rexpat string
734-
if idx := strings.Index(key, ":"); idx >= 0 {
733+
key, rexpat, isRegexp := strings.Cut(key, ":")
734+
if isRegexp {
735735
nt = ntRegexp
736-
rexpat = key[idx+1:]
737-
key = key[:idx]
738736
}
739737

740738
if len(rexpat) > 0 {

0 commit comments

Comments
 (0)