Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions tags/back_url.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package tags

import (
"net/http"

"github.com/gobuffalo/helpers/hctx"
)

// BackURL returns a URL to the referer, if its presend in the
// "Referer" header it will take it from there. Otherwise it will return
// "javascript:history.back()" and rely on the browser history.
func BackURL(help hctx.HelperContext) string {
backURL := "javascript:history.back()"

var req *http.Request
var ok bool
if req, ok = help.Value("request").(*http.Request); !ok {
return backURL
}

if referer := req.Header.Get("Referer"); referer != "" {
backURL = referer
}

return backURL
}
37 changes: 37 additions & 0 deletions tags/back_url_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package tags

import (
"net/http"
"testing"

"github.com/gobuffalo/helpers/helptest"
"github.com/stretchr/testify/require"
)

func TestBackURL(t *testing.T) {

req, _ := http.NewRequest("GET", "https://wawand.co/contact", nil)
req.Header.Add("Referer", "https://gobuffalo.io")

req2, _ := http.NewRequest("GET", "https://wawand.co/contact", nil)

testCases := []struct {
name string
request interface{}
expectedURL string
}{
{name: "RefererIncluded", request: req, expectedURL: "https://gobuffalo.io"},
{name: "RequestNotRequest", request: "not-request", expectedURL: "javascript:history.back()"},
{name: "RequestNotRequest", request: req2, expectedURL: "javascript:history.back()"},
}

for _, testCase := range testCases {
t.Run(testCase.name, func(st *testing.T) {
c := helptest.NewContext()
c.Set("request", testCase.request)

r := require.New(st)
r.Equal(testCase.expectedURL, BackURL(c))
})
}
}
2 changes: 2 additions & 0 deletions tags/tags.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const (
JSKey = "javascriptTag"
LinkToKey = "linkTo"
RemoteLinkToKey = "remoteLinkTo"
BackURLKey = "backURL"
)

// New returns a map of the helpers within this package.
Expand All @@ -24,5 +25,6 @@ func New() hctx.Map {
JSKey: JS,
LinkToKey: LinkTo,
RemoteLinkToKey: RemoteLinkTo,
BackURLKey: BackURL,
}
}