Hi,
Today, I am going to write simple steps to modify url in Golang.
Sometimes in Golang server code, we need to redirect to different endpoint where we are required append few query params or request headers before we do redirect.
Please ignore if there are any mistakes.
package main
import (
"fmt"
"log"
"net/http"
"net/url"
)
func main() {
// This is just some example URL we received in our backend code.
// Now we need to append some query params to it,
// so that we can redirect or hit the newly formed URL.
u := "https://www.example.com/path1/path2"
// Scenario (1):
// We just need to append path. For that we can just append "path" with simple string.
// Before you add "/" check the URL has already or not
pAppendedURL := u + "/pathN"
if isValid, err := IsUrl(pAppendedURL); !isValid {
log.Fatalf("Invalid URL: %v\n", err)
}
fmt.Printf("Appended path param to the URL: %s\n", pAppendedURL)
// Scenario (2):
// We need to append one or more query params.
queryParms := url.Values{}
queryParms.Add("key1", "value1")
queryParms.Add("key2", "value2")
// Append '?' if it does not exists already.
qAppendedURL := u + "?" + queryParms.Encode()
if isValid, err := IsUrl(qAppendedURL); !isValid {
log.Fatalf("Invalid URL: %v\n", err)
}
fmt.Printf("Added query params to the URL: %s\n", qAppendedURL)
// You may want to build request object like below
// and redirect to the URL you built.
req, err := http.NewRequest(http.MethodGet, qAppendedURL, nil)
if err != nil {
log.Fatalf("Failed to create request object: %v\n", err)
}
// Add request headers
req.Header.Add("header1", "value1")
req.Header.Add("header2", "value2")
// So, you can redirect to the URL by new request object
http.Redirect("your response writer goes here", req, qAppendedURL, 304)
}
// IsUrl checks if the URL is valid or not.
// https://stackoverflow.com/questions/25747580/ensure-a-uri-is-valid/25747925#25747925.
func IsUrl(str string) (bool, error) {
u, err := url.Parse(str)
return err == nil && u.Scheme != "" && u.Host != "", err
}
Thank you
Top comments (0)