package echo import ( "net/url" "path" "github.com/labstack/echo/v4" ) // URLBuilder is used to build URLs with optional querystring arguments. This // is used to build URLs to REST resources within handlers. // // This exists because the default Echo reversing logic requires handlers to // hold references to other handlers to be able to build reverse URLs. This is // a bad solution to an ugly problem but as the router currently stands there's // not much that can be done about it. In the future this should go away and be // replaced by something like named routes in echo. type URLBuilder struct { c echo.Context u *url.URL q url.Values } func URLFor(c echo.Context, parts ...string) *URLBuilder { u := &url.URL{ Scheme: "http", Host: c.Request().Host, Path: path.Join(parts...), } if c.Request().TLS != nil { u.Scheme = "https" } return &URLBuilder{c, u, nil} } func (b *URLBuilder) Query(k, v string) *URLBuilder { if b.q == nil { b.q = url.Values{} } b.q.Add(k, v) return b } func (b *URLBuilder) String() string { if b.q != nil { b.u.RawQuery = b.q.Encode() } return b.u.String() }