aboutsummaryrefslogtreecommitdiff
path: root/echo/url_builder.go
diff options
context:
space:
mode:
Diffstat (limited to 'echo/url_builder.go')
-rw-r--r--echo/url_builder.go49
1 files changed, 49 insertions, 0 deletions
diff --git a/echo/url_builder.go b/echo/url_builder.go
new file mode 100644
index 0000000..955ecb5
--- /dev/null
+++ b/echo/url_builder.go
@@ -0,0 +1,49 @@
1package echo
2
3import (
4 "net/url"
5 "path"
6
7 "github.com/labstack/echo/v4"
8)
9
10// URLBuilder is used to build URLs with optional querystring arguments. This
11// is used to build URLs to REST resources within handlers.
12//
13// This exists because the default Echo reversing logic requires handlers to
14// hold references to other handlers to be able to build reverse URLs. This is
15// a bad solution to an ugly problem but as the router currently stands there's
16// not much that can be done about it. In the future this should go away and be
17// replaced by something like named routes in echo.
18type URLBuilder struct {
19 c echo.Context
20 u *url.URL
21 q url.Values
22}
23
24func URLFor(c echo.Context, parts ...string) *URLBuilder {
25 u := &url.URL{
26 Scheme: "http",
27 Host: c.Request().Host,
28 Path: path.Join(parts...),
29 }
30 if c.Request().TLS != nil {
31 u.Scheme = "https"
32 }
33 return &URLBuilder{c, u, nil}
34}
35
36func (b *URLBuilder) Query(k, v string) *URLBuilder {
37 if b.q == nil {
38 b.q = url.Values{}
39 }
40 b.q.Add(k, v)
41 return b
42}
43
44func (b *URLBuilder) String() string {
45 if b.q != nil {
46 b.u.RawQuery = b.q.Encode()
47 }
48 return b.u.String()
49}