dgrijalva / jwt-go

ARCHIVE - Golang implementation of JSON Web Tokens (JWT). This project is now maintained at:
https://github.com/golang-jwt/jwt
MIT License
10.78k stars 997 forks source link

v4 preview 1, "functional options" for constructors don't work as intended outside the package #447

Open stonedu1011 opened 3 years ago

stonedu1011 commented 3 years ago

I understand it's at very early stage, so just want to provide some feedback after my attempt to use it.

We uses similar API designed inspired by (this article)[https://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis] in our team. This approach only works if the functional options takes exported type with exported fields. Otherwise, the constructor is completely not configurable.

Here is the patterns we ends up using, in case we want to keep the Type's field hidden:

type Options func(*Opt)

type Opt struct {
    ConfigurableField1 type
    ConfigurableField2 type
}

type SomeType struct {
    field1 type
    field2 type
}

func New(opts ...Options) *SomeType {
    opt := Opt{
        // defaults
    }
    for _, optFunc := range opts {
        optFunc(&opt)
    }
    return &SomeType {
        field1: opt.ConfigurableField1,
        field2: opt.ConfigurableField2,
    }
}

This is a great library and I hope the V4 reaches a stable state soon.