Cut Strings At The First Separator
Parse host:port and key=value pairs with strings.Cut, which splits at the first separator and reports before, after, and whether a separator was found.
Code
package main
import (
"fmt"
"strings"
)
func main() {
// strings.Cut splits at the first separator only: a before/after/found triple
addr := "db.internal:5432"
host, port, ok := strings.Cut(addr, ":")
fmt.Printf("host=%q port=%q found=%v\n", host, port, ok)
// No separator: the whole string lands in before, after is empty, found is false
noPort, _, found := strings.Cut("localhost", ":")
fmt.Printf("noPort=%q found=%v\n", noPort, found)
// With several separators only the first splits: the rest stays intact in after
first, rest, _ := strings.Cut("k1=v1=k2", "=")
fmt.Printf("first=%q rest=%q\n", first, rest)
// Cutting into after repeatedly walks every k=v field
line := "user=ada,role=admin,team=core"
for {
field, next, more := strings.Cut(line, ",")
k, v, _ := strings.Cut(field, "=")
fmt.Printf("%s=%s\n", k, v)
if !more {
break
}
line = next
}
}How the snippet works
Under the hood: the function main.
The one repetition in this snippet is the loop for.
Points of care
- Built-in APIs only, so there is no supply chain to vet.
Using it
The demo output is labeled (host=, noPort=, first=), so each line traces straight back to the statement that printed it.
Key statements
noPort, _, found := strings.Cut("localhost", ":")
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- What does Cut Strings At The First Separator print when run?
- No setup needed: run the file and look for labeled lines like `host=`, `noPort=`, `first=` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.