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
+18.2k Golang : Aligning strings to right, left and center with fill example
+25k Golang : Convert long hexadecimal with strconv.ParseUint example
+30.5k Golang : Download file example
+12k Golang : Flush and close file created by os.Create and bufio.NewWriter example
+12k Golang : List running EC2 instances and descriptions
+5.4k Golang : Detect words using using consecutive letters in a given string
+10.9k CodeIgniter : How to check if a session exist in PHP?
+9.1k Golang : Timeout example
+5.6k CodeIgniter/PHP : Remove empty lines above RSS or ATOM xml tag
+7.5k Golang : Example of how to detect which type of script a word belongs to
+19.3k Golang : Example for DSA(Digital Signature Algorithm) package functions
+32.6k Golang : How to check if a date is within certain range?