Skip to content

Commit

Permalink
feat: add Basic Auth option
Browse files Browse the repository at this point in the history
  • Loading branch information
jsteenb2 committed Jul 7, 2024
1 parent 525a70f commit 41d663f
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 5 deletions.
29 changes: 27 additions & 2 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,18 +30,34 @@ var (
}()
)

func WithBasicAuth(user, pass string) func(*ClientHTTP) {
return func(c *ClientHTTP) {
c.authFn = func(r *http.Request) error {
r.SetBasicAuth(user, pass)
return nil
}
}
}

type ClientHTTP struct {
addr string
origin string
c *http.Client
authFn func(r *http.Request) error
}

func NewClientHTTP(addr, origin string, c *http.Client) *ClientHTTP {
return &ClientHTTP{
func NewClientHTTP(addr, origin string, c *http.Client, opts ...func(*ClientHTTP)) *ClientHTTP {
out := ClientHTTP{
addr: addr,
origin: origin,
c: c,
authFn: func(r *http.Request) error { return nil },
}
for _, o := range opts {
o(&out)
}

return &out
}

// Foo API types
Expand Down Expand Up @@ -109,11 +125,20 @@ func (c *ClientHTTP) DelFoo(ctx context.Context, id string) (RespBody[any], erro
return RespBody[any]{}, errors.Wrap(err)
}

err = c.authFn(req)
if err != nil {
return RespBody[any]{}, errors.Wrap(err)
}

resp, err := doJSON[any](c.c, req)
return resp, errors.Wrap(err)
}

func (c *ClientHTTP) doFooReq(req *http.Request) (RespBody[ResourceFooAttrs], error) {
if err := c.authFn(req); err != nil {
return RespBody[ResourceFooAttrs]{}, errors.Wrap(err)
}

resp, err := doJSON[ResourceFooAttrs](c.c, req)
return resp, errors.Wrap(err)
}
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ module github.com/jsteenb2/allsrvc

go 1.22

require github.com/jsteenb2/errors v0.2.0
require github.com/jsteenb2/errors v0.3.0
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
github.com/jsteenb2/errors v0.2.0 h1:7LImy2u+6CAKJnw6Ug8xuW/THKH2fwWf1BAUwQuNaeQ=
github.com/jsteenb2/errors v0.2.0/go.mod h1:vLm/10zo41mY2s7yGpB654h094ShSoG9LKwbivG0joU=
github.com/jsteenb2/errors v0.3.0 h1:m45UhWJUnlrHMLu2JA9xYDJ7PaYwkdwoowTZZ+34hSs=
github.com/jsteenb2/errors v0.3.0/go.mod h1:vLm/10zo41mY2s7yGpB654h094ShSoG9LKwbivG0joU=

0 comments on commit 41d663f

Please sign in to comment.