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
+5.8k Linux/MacOSX : Search for files by filename and extension with find command
+21.3k Golang : GORM create record or insert new record into database example
+29.5k Golang : How to get HTTP request header information?
+12.6k Golang : Convert int(year) to time.Time type
+13.7k Golang : Compress and decompress file with compress/flate example
+18.7k Golang : When to use public and private identifier(variable) and how to make the identifier public or private?
+14.3k Golang : Execute function at intervals or after some delay
+17.3k Golang : [json: cannot unmarshal object into Go value of type]
+13.5k Golang : Get dimension(width and height) of image file
+11k Golang : How to pipe input data to executing child process?
+8.1k Golang : Count leading or ending zeros(any item of interest) example