Parsing turns a raw URL string into a structured URL value. A URL holds Scheme, Host, and Path fields; Parse returns a pointer to that value plus an error, while String reassembles the fields for display or logging. section 2.1.1
Use Parse at a program boundary, then check its error before reading the returned URL. A nil error means parsing succeeded; a non-nil error means callers should not use the other result. Because Parse is exported, another package calls it as url.Parse. section 2.1.2
Parse the scheme, host, and optional path
Split first on "://" with strings.Cut. If that separator is absent, return nil and an error such as "missing scheme". Otherwise, split the remaining text once on "/" to obtain the host and path. Ignore Cut’s found result for this second split because a path is optional: https://github.com can still parse successfully. Store the pieces in a new URL and return it with a nil error. section 2.3.5
Listing 2.6 Fixing the Parse function (url/url.go)
package url
import (
"errors"
"fmt"
"strings"
)
. . .
func Parse(rawURL string) (*URL, error) {
scheme, rest, ok := strings.Cut(rawURL, "://") #1
if !ok {
return nil, errors.New("missing scheme") #2
}
host, path, _ := strings.Cut(rest, "/") #3
return &URL{
Scheme: scheme,
Host: host,
Path: path,
}, nil
}
The implementation makes the control flow explicit: reject a missing scheme, then construct a URL from the two cuts. section 2.3.5
Test successful parsing by comparing the returned URL with an expected URL value. Stop the test with Fatalf when Parse returns an error, because continuing could dereference a nil pointer; use Errorf for a mismatched result so the test can report the failure. A separate test can verify String reassembles the expected URL text. section 2.3.1
Keep this parser’s contract clear:
- Require a scheme separator; inputs without one produce an error. section 2.3.5
- Accept a URL with no path rather than treating the absent slash as a failure. section 2.3.5
- Use the parsed fields only after confirming that err is nil. section 2.1.2












