Go中的URL构建器/查询构建器

huangapple go评论86阅读模式
英文:

URL Builder/Query builder in Go

问题

我对通过浏览器或CLI动态接收用户输入作为参数,并将这些参数传递给REST API调用,并使用Go动态构建URL以最终获取JSON数据很感兴趣。

我想了解一些在Go中可以帮助我实现这一目标的技术。我认为一种理想的方式是使用一个map,将参数键和相应的值填充到map中,然后遍历map并将其附加到URL字符串中。但是,当涉及到动态获取参数并填充map时,我不太确定如何在Go中实现。有人可以帮我提供一些Go代码片段吗?

请求示例:

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

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://&lt;IP&gt;:port?api=fetchJsonData&amp;arg1=val1&amp;arg2=val2&amp;arg3=val3.....&amp;argn=valn

答案1

得分: 150

这是要翻译的内容:

已经有url.URL可以处理这种情况。

对于HTTP处理程序(传入请求),它是http.Request的一部分(通过req.URL.Query()访问)。

以下是官方文档中的一个很好的示例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)
英文:

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(&quot;http://bing.com/search?q=dotnet&quot;)
if err != nil {
	log.Fatal(err)
}
u.Scheme = &quot;https&quot;
u.Host = &quot;google.com&quot;
q := u.Query()
q.Set(&quot;q&quot;, &quot;golang&quot;)
u.RawQuery = q.Encode()
fmt.Println(u)

答案2

得分: 15

以下是翻译好的内容:

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())
}

返回:

https://example.com

英文:

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

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

package main

import (
	&quot;fmt&quot;
	&quot;net/url&quot;
)

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

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

returns:

https://example.com

答案3

得分: 8

url.Values{} 提供了一个构建查询参数的接口。你可以内联构建,也可以使用.Add来添加动态属性:

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=...
英文:

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

queryParams := url.Values{
	&quot;checkin&quot;:  {request.CheckIn},
	&quot;checkout&quot;: {request.CheckOut},
}

if request.ReservationId {
	queryParams.Add(&quot;reservationId&quot;, request.ReservationId)
}

url := &quot;https://api.example?&quot; + queryParams.Encode() // checkin=...&amp;checkout=...

答案4

得分: 0

package main

import (
    "fmt"
    "net/url"
)

func main() {
    partofUrl := &url.URL{
        Scheme: "https",
        Host:   "test.dev",
        Path:   "/abc",
    }
    fmt.Println(partofUrl.String()) //https://test.dev/abc
}
package main

import (
    "fmt"
    "net/url"
)

func main() {
    partofUrl := &url.URL{
        Scheme: "https",
        Host:   "test.dev",
        Path:   "/abc",
    }
    fmt.Println(partofUrl.String()) //https://test.dev/abc
}
英文:
package main

import (
    &quot;fmt&quot;
    &quot;net/url&quot;
)

func main() {

 partofUrl := &amp;url.URL{
	 Scheme: &quot;https&quot;,
	 Host: &quot;test.dev&quot;,
	 Path: &quot;/abc&quot;,
}
fmt.Println(partofUrl.String()) //https://test.dev/abc
    
}

huangapple
  • 本文由 发表于 2014年11月18日 08:16:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/26984420.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定