URL Builder/Query builder in Go

RestUrlGo

Rest Problem Overview


I am interested in dynamically taking arguments from the user as input through a browser or a CLI to pass in those parameters to the REST API call and hence construct the URL dynamically using Go which is going to ultimately fetch me some JSON data.

I want to know some techniques in Go which could help me do that. One ideal way I thought was to use a map and populate it with arguments keys and corresponding values and iterate over it and append it to the URL string. But when it comes to dynamically taking the arguments and populating the map, I am not very sure how to do that in Go. Can someone help me out with some code snippet in Go?

Request example:

http://<IP>:port?api=fetchJsonData&arg1=val1&arg2=val2&arg3=val3.....&argn=valn

Rest Solutions


Solution 1 - Rest

There's already url.URL that handles that kind of things for you.

For http handlers (incoming requests) it's a part of http.Request (access it with req.URL.Query()).

A very good example from the official docs:

u, err := url.Parse("http://bing.com/search?q=dotnet")
if err != nil {
	log.Fatal(err)
}
u.Scheme = "https"
u.Host = "google.com"
q := u.Query()
q.Set("q", "golang")
u.RawQuery = q.Encode()
fmt.Println(u)

Solution 2 - Rest

https://github.com/golang/go/issues/17340#issuecomment-251537687

https://play.golang.org/p/XUctl_odTSb

package main

import (
	"fmt"
	"net/url"
)

func someURL() string {
	url := url.URL{
		Scheme: "https",
		Host:   "example.com",
	}
	return url.String()
}

func main() {
	fmt.Println(someURL())
}

returns:

https://example.com

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpsbitsView Question on Stackoverflow
Solution 1 - RestOneOfOneView Answer on Stackoverflow
Solution 2 - Rest030View Answer on Stackoverflow