builder_gen.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // This file is auto-generated by jwt/internal/cmd/gentoken/main.go. DO NOT EDIT
  2. package jwt
  3. import (
  4. "time"
  5. "github.com/pkg/errors"
  6. )
  7. // Builder is a convenience wrapper around the New() constructor
  8. // and the Set() methods to assign values to Token claims.
  9. // Users can successively call Claim() on the Builder, and have it
  10. // construct the Token when Build() is called. This alleviates the
  11. // need for the user to check for the return value of every single
  12. // Set() method call.
  13. // Note that each call to Claim() overwrites the value set from the
  14. // previous call.
  15. type Builder struct {
  16. claims []*ClaimPair
  17. }
  18. func NewBuilder() *Builder {
  19. return &Builder{}
  20. }
  21. func (b *Builder) Claim(name string, value interface{}) *Builder {
  22. b.claims = append(b.claims, &ClaimPair{Key: name, Value: value})
  23. return b
  24. }
  25. func (b *Builder) Audience(v []string) *Builder {
  26. return b.Claim(AudienceKey, v)
  27. }
  28. func (b *Builder) Expiration(v time.Time) *Builder {
  29. return b.Claim(ExpirationKey, v)
  30. }
  31. func (b *Builder) IssuedAt(v time.Time) *Builder {
  32. return b.Claim(IssuedAtKey, v)
  33. }
  34. func (b *Builder) Issuer(v string) *Builder {
  35. return b.Claim(IssuerKey, v)
  36. }
  37. func (b *Builder) JwtID(v string) *Builder {
  38. return b.Claim(JwtIDKey, v)
  39. }
  40. func (b *Builder) NotBefore(v time.Time) *Builder {
  41. return b.Claim(NotBeforeKey, v)
  42. }
  43. func (b *Builder) Subject(v string) *Builder {
  44. return b.Claim(SubjectKey, v)
  45. }
  46. // Build creates a new token based on the claims that the builder has received
  47. // so far. If a claim cannot be set, then the method returns a nil Token with
  48. // a en error as a second return value
  49. func (b *Builder) Build() (Token, error) {
  50. tok := New()
  51. for _, claim := range b.claims {
  52. if err := tok.Set(claim.Key.(string), claim.Value); err != nil {
  53. return nil, errors.Wrapf(err, `failed to set claim %q`, claim.Key.(string))
  54. }
  55. }
  56. return tok, nil
  57. }