liveBook · Manning

URL

As explained in Go by Example

A URL is a structured identifier for locating a resource through a network-access scheme, host, and optional path.

A URL is a structured identifier whose parts locate a resource through a scheme, host, and optional path. A Go URL value stores these parts, while Parse converts a string into a *URL and String reassembles it. section 2.1.1

Parsing and rebuilding a URL

Given https://github.com/inancgumus, Parse produces Scheme "https", Host "github.com", and Path "inancgumus". Calling String on that value returns https://github.com/inancgumus. section 2.1.1 section 2.3.1

Implement URL handling incrementally:

  • Represent the parsed value with a URL struct containing Scheme, Host, and Path string fields. section 2.1.1
  • Split the raw string at the first colon to obtain the scheme and remainder; return an error when the scheme is missing. section 2.5.5
  • Treat a remainder without // as an opaque URL, returning only its scheme; otherwise remove // and split the remainder into host and path. section 2.5.5
  • Test Parse against expected URL values and test String against the expected reconstructed string. section 2.3.1

Parsing tests should stop with Fatalf when an error leaves no valid URL to inspect. Use Errorf for mismatches that allow the test to continue and report additional failures. The failfast flag instead stops the overall test run at its first reported failure when isolating one problem. section 2.3.1 section 2.5.5

String slicing makes the parser concise, but slicing operates on bytes. Multibyte Unicode characters can span several bytes, so careless string boundaries can split a character. section 2.5.5

Figure 2.1 The url package’s overview. Parse returns a pointer to a URL value that contains the parsed URL’s parts. String reassembles the URL value as a string.
A screenshot of a computer

AI-generated content may be incorrect.

Trace how Parse returns a pointer to structured URL data and how String turns that data back into a URL string. section 2.1.1

How Go by Example covers it

How deep it goes
Descends from URL fields to scheme slicing, opaque URLs, host-path parsing, errors, and test control flow.
Examples
Uses https://github.com/inancgumus, data:text/plain, parsed URL structs, and Parse and String tests.
What you can do after
Build it from scratch by parsing regular and opaque URLs, rebuilding strings, and testing failures with appropriate diagnostics.
How it connects
Connects URL parsing with structs, methods, string slicing, error handling, and unit testing.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go by Example. The section links point to the parts of the book it draws on.