Golang : Get current URL example
One of the common tasks that a web application developer will encounter is on how to get the currently viewed URL by a visitor. Being able to detect currently viewed URL will help in coding the customization of the page content to suit the visitor and improve UX such as displaying relevant navigation path or bread crumbs.
Below is an example function that returns the full URL (including segments) of the page being currently viewed.
package main
import (
"net/http"
"os"
)
func CurrentURL(r *http.Request) string {
hostname, err := os.Hostname()
if err != nil {
panic(err)
}
return hostname + r.URL.Path
}
func DisplayCurrentURL(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("[current url] : " + CurrentURL(r) + "\r\n"))
}
func main() {
// http.Handler
mux := http.NewServeMux()
mux.HandleFunc("/", DisplayCurrentURL)
http.ListenAndServe("", mux)
}
Run this code and point your web browser to the server and enter a few URL segments to test it out yourself.
Happy coding!
References:
https://www.socketloop.com/references/golang-os-hostname-function-example
https://www.socketloop.com/tutorials/golang-parsing-or-breaking-down-url
See also : Golang : Get final or effective URL with Request.URL example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+11.5k Swift : Convert (cast) Float to String
+33.5k Golang : How to check if slice or array is empty?
+25.8k Golang : How to read integer value from standard input ?
+9.3k Golang : Launch Mac OS X Preview (or other OS) application from your program example
+14k Golang : Fix cannot use buffer (type bytes.Buffer) as type io.Writer(Write method has pointer receiver) error
+12.4k Golang : Extract part of string with regular expression
+18k Golang : Convert IPv4 address to decimal number(base 10) or integer
+10.2k Golang : Convert file content to Hex
+12.6k Golang : Pass database connection to function called from another package and HTTP Handler
+11.7k Golang : Verify Linux user password again before executing a program example
+14.9k Golang : Search folders for file recursively with wildcard support
+25.6k Golang : missing Mercurial command