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
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,18 @@ u := webtools.CreateURL("example.org", "/some/path", map[string]string {
})
```

There is also the `Origins` convenience function for parsing the user-agent
of an `http.Request` and creating a struct of interesting values regarding the
request.

```go
ua := webtools.Origins(r)

fmt.Println(ua.String()) # e.g. curl/unknown
fmt.Println(ua.Anchor()) # e.g. example.org/path/to/page
fmt.Println(ua.From()) # e.g. 10.0.0.1
```

#### package webtools/middles

Provides a generic sessions `http.Handler` which can be used to set and validate
Expand Down
13 changes: 11 additions & 2 deletions useragent.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,18 @@ type Origin struct {
UserAgent useragent.UserAgent
}

// From returns a parsed version of the Referer headers, including the domain
// and path without the protocol or query.
// From returns the value of the X-Forwarded-For if set, otherwise defaulting
// to the Host header.
func (o *Origin) From() string {
if o.Forward != "" {
return o.Forward
}
return o.Host
}

// Anchor returns a parsed version of the Referer headers, including the domain
// and path without the protocol or query.
func (o *Origin) Anchor() string {
if o.Reference == "" {
return "-"
}
Expand Down
25 changes: 24 additions & 1 deletion useragent_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,29 @@ import (
func TestOrigin_From(t *testing.T) {
t.Parallel()

t.Run("forward set", func(t *testing.T) {
o := &Origin{
Host: "10.0.0.1",
Forward: "example.com",
}

s := o.From()
must.Eq(t, "example.com", s)
})

t.Run("not set", func(t *testing.T) {
o := &Origin{
Host: "10.0.0.1",
}

s := o.From()
must.Eq(t, "10.0.0.1", s)
})
}

func TestOrigin_Anchor(t *testing.T) {
t.Parallel()

cases := []struct {
name string
reference string
Expand All @@ -26,7 +49,7 @@ func TestOrigin_From(t *testing.T) {
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
o := &Origin{Reference: tc.reference}
must.Eq(t, tc.exp, o.From())
must.Eq(t, tc.exp, o.Anchor())
})
}
}
Expand Down