Skip to content

net/url: add URL.ForceFragment like ForceQuery for empty fragments to stringify with '#' #29603

@Gregable

Description

@Gregable

What version of Go are you using (go version)?

go version go1.11.2 linux/amd64

What did you do?

import (
  "fmt"
  "log"
  "net/url"
)

func main() {
    u, err := url.Parse("http://example.com/#")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(u.String())
    fmt.Println(u.Fragment)
}

What did you expect to see?

http://example.com/#
#

What did you see instead?

http://example.com/

What's the issue?

At first glance, http://example.com/# and http://example.com/ are logically the same URL. This is largely true in the context of a browser navigating to that URL as typed into the URL bar, but they are subtly different in a link. If a user clicks the following link:

<a href="http://example.com/#">foo</a>

If the document URL (or <base href>) is http://example.com/ then this click does not cause a navigation - it is a within document link. However, if the link was instead to:

<a href="http://example.com/">foo</a>

Then clicking it causes a navigation. A reload really, but still a navigation.

This becomes more of an issue when net/url is used to resolve a relative URL:

<html>
<head>
  <base href="http://example.com/">
</head>
<body>
  <a href="/">reload</a>
  <a href="#">inert</a>
</body>
</html>
base, _ = url.Parse("http://example.com/")
nav, _ = base.Parse("/")
local, _ = base.Parse("#")

nav and local are now equal, which means it's not possible to distinguish a document local link and a navigation link.

Metadata

Metadata

Assignees

No one assigned

    Labels

    FeatureRequestIssues asking for a new feature that does not need a proposal.FrozenDueToAgeNeedsDecisionFeedback is required from experts, contributors, and/or the community before a change can be made.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions