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
+8.4k Golang : Get final or effective URL with Request.URL example
+18.2k Golang : How to log each HTTP request to your web server?
+9.3k Golang : io.Reader causing panic: runtime error: invalid memory address or nil pointer dereference
+32.7k Golang : Math pow(the power of x^y) example
+14.4k Golang : Chunk split or divide a string into smaller chunk example
+9.5k Golang : How to control fmt or log print format?
+11.3k Golang : Read until certain character to break for loop
+5.2k Golang : Check if a word is countable or not
+10.1k Golang : Translate language with language package example
+17.2k Golang : Get input from keyboard
+4.5k Linux/MacOSX : Search and delete files by extension
+10.8k Golang : Create matrix with Gonum Matrix package example