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
+17.4k Golang : Find IP address from string
+13.7k Golang : Submit web forms without browser by http.PostForm example
+4.1k Which content-type(MIME type) to use for JSON data
+7.2k Findstr command the Grep equivalent for Windows
+13.4k Golang : Recombine chunked files example
+12.8k Golang : How to determine if a year is leap year?
+10.2k Golang : Calculate Relative Strength Index(RSI) example
+4.5k Golang : Qt update UI elements with core.QCoreApplication_ProcessEvents
+4k Linux/MacOSX : How to symlink a file?
+6.1k Golang : How to fix html/template : "somefile" is undefined error?
+21.3k Golang : Repeat a character by multiple of x factor
+22.3k Find and replace a character in a string in Go