DEV Community

Ramu Mangalarapu
Ramu Mangalarapu

Posted on

3 2

Modifications to url in Golang

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
}

Enter fullscreen mode Exit fullscreen mode

Thank you

Billboard image

Deploy and scale your apps on AWS and GCP with a world class developer experience

Coherence makes it easy to set up and maintain cloud infrastructure. Harness the extensibility, compliance and cost efficiency of the cloud.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay