Skip to content

Instantly share code, notes, and snippets.

@karl-gustav
Created September 25, 2022 20:42
Show Gist options
  • Save karl-gustav/001e05e70527986f8b6d11f675ed610c to your computer and use it in GitHub Desktop.
Save karl-gustav/001e05e70527986f8b6d11f675ed610c to your computer and use it in GitHub Desktop.
Get full URL from http request in go
func fullURL(r *http.Request, overridePath ...string) string {
scheme := "http"
if r.TLS != nil {
scheme = "https"
}
if len(overridePath) != 0 {
return fmt.Sprintf("%s://%s%s", scheme, r.Host, overridePath[0])
}
return fmt.Sprintf("%s://%s%s?%s#%s", scheme, r.Host, r.URL.Path, r.URL.RawQuery, r.URL.Fragment)
}
@guettli
Copy link

guettli commented Apr 29, 2024

Is there already a package which provides that?

@karl-gustav
Copy link
Author

@guettli Let me know if you find one. I can post the link here if anybody else finds this.

@mishankov
Copy link

This version handles empty query and fragment

func fullURL(r *http.Request) string {
	builder := strings.Builder{}

	if r.TLS != nil {
		builder.WriteString("https://")
	} else {
		builder.WriteString("http://")
	}

	builder.WriteString(r.Host)
	builder.WriteString(r.URL.Path)

	if r.URL.RawQuery != "" {
		builder.WriteString("?" + r.URL.RawQuery)
	}

	if r.URL.Fragment != "" {
		builder.WriteString("#" + r.URL.Fragment)
	}

	return builder.String()
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment