Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URL Builder/Query builder in Go

Tags:

rest

url

go

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
like image 662
psbits Avatar asked Nov 18 '14 00:11

psbits


3 Answers

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)
like image 98
OneOfOne Avatar answered Nov 14 '22 01:11

OneOfOne


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

like image 26
030 Avatar answered Nov 14 '22 01:11

030


url.Values{} provides an interface for building query params. You can construct inline and/or use .Add for dynamic properties:

queryParams := url.Values{
    "checkin":  {request.CheckIn},
    "checkout": {request.CheckOut},
}

if request.ReservationId {
    queryParams.Add("reservationId", request.ReservationId)
}

url := "https://api.example?" + queryParams.Encode() // checkin=...&checkout=...
like image 4
Sam Berry Avatar answered Nov 14 '22 03:11

Sam Berry