Skip to content

Commit

Permalink
switch to using any instead of interface{}
Browse files Browse the repository at this point in the history
  • Loading branch information
pitabwire committed Jan 20, 2024
1 parent d3ae38a commit f311084
Show file tree
Hide file tree
Showing 17 changed files with 48 additions and 49 deletions.
17 changes: 8 additions & 9 deletions authentication.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ const ctxKeyAuthentication = contextKey("authenticationKey")
// AuthenticationClaims Create a struct that will be encoded to a JWT.
// We add jwt.StandardClaims as an embedded type, to provide fields like expiry time
type AuthenticationClaims struct {
ProfileID string `json:"sub,omitempty"`
Ext map[string]interface{} `json:"ext,omitempty"`
ProfileID string `json:"sub,omitempty"`
Ext map[string]any `json:"ext,omitempty"`
jwt.RegisteredClaims
}

Expand Down Expand Up @@ -129,10 +129,9 @@ func ClaimsFromContext(ctx context.Context) *AuthenticationClaims {

// ClaimsFromMap extracts authentication claims from the supplied map if they exist
func ClaimsFromMap(m map[string]string) *AuthenticationClaims {
var authenticationClaims AuthenticationClaims

authenticationClaims = AuthenticationClaims{
Ext: map[string]interface{}{},
authenticationClaims := AuthenticationClaims{
Ext: map[string]any{},
}

for key, val := range m {
Expand Down Expand Up @@ -188,7 +187,7 @@ type JSONWebKeys struct {
X5c []string `json:"x5c"`
}

func (s *Service) getPemCert(token *jwt.Token) (interface{}, error) {
func (s *Service) getPemCert(token *jwt.Token) (any, error) {
config, ok := s.Config().(ConfigurationOAUTH2)
if !ok {
return nil, errors.New("could not cast config for oauth2 settings")
Expand Down Expand Up @@ -312,8 +311,8 @@ func grpcJwtTokenExtractor(ctx context.Context) (string, error) {

// UnaryAuthInterceptor Simple grpc interceptor to extract the jwt supplied via authorization bearer token and verify the authentication claims in the token
func (s *Service) UnaryAuthInterceptor(audience string, issuer string) grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{},
info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
return func(ctx context.Context, req any,
info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
jwtToken, err := grpcJwtTokenExtractor(ctx)
if err != nil {
return nil, err
Expand Down Expand Up @@ -342,7 +341,7 @@ func (s *serverStreamWrapper) Context() context.Context {

// StreamAuthInterceptor An authentication claims extractor that will always verify the information flowing in the streams as true jwt claims
func (s *Service) StreamAuthInterceptor(audience string, issuer string) grpc.StreamServerInterceptor {
return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
return func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
localServerStream := ss
authClaim := ClaimsFromContext(localServerStream.Context())
if authClaim == nil {
Expand Down
4 changes: 2 additions & 2 deletions authorization.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ func AuthHasAccess(ctx context.Context, action string, subject string) (bool, er
return false, errors.New("only authenticated requsts should be used to check authorization")
}

payload := map[string]interface{}{
payload := map[string]any{
"namespace": authClaims.TenantId(),
"object": authClaims.PartitionId(),
"relation": action,
Expand All @@ -39,7 +39,7 @@ func AuthHasAccess(ctx context.Context, action string, subject string) (bool, er
return false, fmt.Errorf(" invalid response status %d had message %s", status, string(result))
}

var response map[string]interface{}
var response map[string]any
err = json.Unmarshal(result, &response)
if err != nil {
return false, err
Expand Down
4 changes: 2 additions & 2 deletions authorization_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ func authorizationControlListWrite(ctx context.Context, writeServerURL string, a
return errors.New("only authenticated requsts should be used to check authorization")
}

payload := map[string]interface{}{
payload := map[string]any{
"namespace": authClaims.TenantId(),
"object": authClaims.PartitionId(),
"relation": action,
Expand All @@ -36,7 +36,7 @@ func authorizationControlListWrite(ctx context.Context, writeServerURL string, a
return fmt.Errorf(" invalid response status %d had message %s", status, string(result))
}

var response map[string]interface{}
var response map[string]any
err = json.Unmarshal(result, &response)
if err != nil {
return err
Expand Down
2 changes: 1 addition & 1 deletion client.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import (

// InvokeRestService convenience method to call a http endpoint and utilize the raw results
func (s *Service) InvokeRestService(ctx context.Context,
method string, endpointURL string, payload map[string]interface{},
method string, endpointURL string, payload map[string]any,
headers map[string][]string) (int, []byte, error) {

if headers == nil {
Expand Down
2 changes: 1 addition & 1 deletion common.go
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,6 @@ func GetMacAddress() string {
}

// ConfigProcess convenience method to processFunc configs
func ConfigProcess(prefix string, config interface{}) error {
func ConfigProcess(prefix string, config any) error {
return envconfig.Process(prefix, config)
}
4 changes: 2 additions & 2 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@ import (
)

// Config Option that helps to specify or override the configuration object of our service.
func Config(config interface{}) Option {
func Config(config any) Option {
return func(s *Service) {
s.configuration = config
}
}

func (s *Service) Config() interface{} {
func (s *Service) Config() any {
return s.configuration
}

Expand Down
4 changes: 2 additions & 2 deletions datastore.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ func DBPropertiesToMap(props json.Marshaler) map[string]string {
return payload
}

properties := make(map[string]interface{})
properties := make(map[string]any)
payloadValue, _ := props.MarshalJSON()
err := json.Unmarshal(payloadValue, &properties)
if err != nil {
Expand Down Expand Up @@ -82,7 +82,7 @@ func DBPropertiesFromMap(propsMap map[string]string) datatypes.JSONMap {
continue
}

var prop interface{}
var prop any
err := json.Unmarshal([]byte(val), prop)
if err != nil {
continue
Expand Down
8 changes: 4 additions & 4 deletions events.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,13 @@ type EventI interface {
Name() string

// PayloadType determines the type of payload the event uses. This is useful for decoding queue data.
PayloadType() interface{}
PayloadType() any

// Validate enables automatic validation of payload supplied to the event without handling it in the execute block
Validate(ctx context.Context, payload interface{}) error
Validate(ctx context.Context, payload any) error

// Execute performs all the logic required to action a step in the sequence of events required to achieve the end goal.
Execute(ctx context.Context, payload interface{}) error
Execute(ctx context.Context, payload any) error
}

// RegisterEvents Option to write an event or list of events into the service registry for future use.
Expand All @@ -46,7 +46,7 @@ func RegisterEvents(events ...EventI) Option {
}

// Emit a simple method used to deploy
func (s *Service) Emit(ctx context.Context, name string, payload interface{}) error {
func (s *Service) Emit(ctx context.Context, name string, payload any) error {

payloadBytes, err := json.Marshal(payload)

Expand Down
6 changes: 3 additions & 3 deletions events_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,20 +18,20 @@ func (event *MessageToTest) Name() string {
return "message.to.test"
}

func (event *MessageToTest) PayloadType() interface{} {
func (event *MessageToTest) PayloadType() any {
pType := ""
return &pType
}

func (event *MessageToTest) Validate(ctx context.Context, payload interface{}) error {
func (event *MessageToTest) Validate(ctx context.Context, payload any) error {
if _, ok := payload.(*string); !ok {
return fmt.Errorf(fmt.Sprintf(" payload is %T not of type %T", payload, event.PayloadType()))
}

return nil
}

func (event *MessageToTest) Execute(ctx context.Context, payload interface{}) error {
func (event *MessageToTest) Execute(ctx context.Context, payload any) error {
message := payload.(*string)
logger := logrus.WithField("payload", message).WithField("type", event.Name())
logger.Info("handling event")
Expand Down
2 changes: 1 addition & 1 deletion internal/queue.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package internal
import "context"

// AckID is the identifier of a message for purposes of acknowledgement.
type AckID interface{}
type AckID any

// Message is data that moves around between client and server
type Message struct {
Expand Down
10 changes: 5 additions & 5 deletions jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ func (s *Service) RegisterForJwt(ctx context.Context) error {
// This is useful for situations where one may need to register external applications for access token generation
func (s *Service) RegisterForJwtWithParams(ctx context.Context,
oauth2ServiceAdminHost string, clientName string, clientSecret string,
scope string, audienceList []string, metadata map[string]string) (map[string]interface{}, error) {
scope string, audienceList []string, metadata map[string]string) (map[string]any, error) {
oauth2AdminURI := fmt.Sprintf("%s%s", oauth2ServiceAdminHost, "/admin/clients")
oauth2AdminIDUri := fmt.Sprintf("%s?client_name=%s", oauth2AdminURI, url.QueryEscape(clientName))

Expand All @@ -59,7 +59,7 @@ func (s *Service) RegisterForJwtWithParams(ctx context.Context,
return nil, fmt.Errorf("invalid existing clients check response : %s", response)
}

var existingClients []map[string]interface{}
var existingClients []map[string]any
err = json.Unmarshal(response, &existingClients)
if err != nil {
s.L().WithError(err).WithField("payload", string(response)).
Expand All @@ -72,7 +72,7 @@ func (s *Service) RegisterForJwtWithParams(ctx context.Context,
}

metadata["cc_bot"] = "true"
payload := map[string]interface{}{
payload := map[string]any{
"client_name": url.QueryEscape(clientName),
"client_secret": url.QueryEscape(clientSecret),
"grant_types": []string{"client_credentials"},
Expand Down Expand Up @@ -100,7 +100,7 @@ func (s *Service) RegisterForJwtWithParams(ctx context.Context,
return nil, fmt.Errorf("invalid registration response : %s", response)
}

var newClient map[string]interface{}
var newClient map[string]any
err = json.Unmarshal(response, &newClient)
if err != nil {
s.L().WithError(err).Error("could not un marshal new client")
Expand All @@ -116,7 +116,7 @@ func (s *Service) UnRegisterForJwt(ctx context.Context,

oauth2AdminURI := fmt.Sprintf("%s%s/%s", oauth2ServiceAdminHost, "/admin/clients", clientID)

status, result, err := s.InvokeRestService(ctx, http.MethodDelete, oauth2AdminURI, make(map[string]interface{}), nil)
status, result, err := s.InvokeRestService(ctx, http.MethodDelete, oauth2AdminURI, make(map[string]any), nil)
if err != nil {
s.L().WithContext(ctx).
WithError(err).
Expand Down
8 changes: 4 additions & 4 deletions localization.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,17 @@ func (s *Service) Bundle() *i18n.Bundle {
}

// Translate performs a quick translation based on the supplied message id
func (s *Service) Translate(request interface{}, messageId string) string {
return s.TranslateWithMap(request, messageId, map[string]interface{}{})
func (s *Service) Translate(request any, messageId string) string {
return s.TranslateWithMap(request, messageId, map[string]any{})
}

// TranslateWithMap performs a translation with variables based on the supplied message id
func (s *Service) TranslateWithMap(request interface{}, messageId string, variables map[string]interface{}) string {
func (s *Service) TranslateWithMap(request any, messageId string, variables map[string]any) string {
return s.TranslateWithMapAndCount(request, messageId, variables, 1)
}

// TranslateWithMapAndCount performs a translation with variables based on the supplied message id and can pluralize
func (s *Service) TranslateWithMapAndCount(request interface{}, messageId string, variables map[string]interface{}, count int) string {
func (s *Service) TranslateWithMapAndCount(request any, messageId string, variables map[string]any, count int) string {

var languageSlice []string

Expand Down
8 changes: 4 additions & 4 deletions localization_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ func TestTranslations(t *testing.T) {
DefaultMessage: &i18n.Message{
ID: "Example",
},
TemplateData: map[string]interface{}{
TemplateData: map[string]any{
"Name": "Air",
},
PluralCount: 1,
Expand All @@ -38,7 +38,7 @@ func TestTranslations(t *testing.T) {
DefaultMessage: &i18n.Message{
ID: "Example",
},
TemplateData: map[string]interface{}{
TemplateData: map[string]any{
"Name": "Air",
},
PluralCount: 1,
Expand Down Expand Up @@ -66,13 +66,13 @@ func TestTranslationsHelpers(t *testing.T) {
return
}

englishVersion = srv.TranslateWithMap("en", "Example", map[string]interface{}{"Name": "MapMan"})
englishVersion = srv.TranslateWithMap("en", "Example", map[string]any{"Name": "MapMan"})
if englishVersion != "MapMan has nothing" {
t.Errorf("Localizations didn't quite work like they should, found : %s expected : %s", englishVersion, "MapMan has nothing")
return
}

englishVersion = srv.TranslateWithMapAndCount("en", "Example", map[string]interface{}{"Name": "CountMen"}, 2)
englishVersion = srv.TranslateWithMapAndCount("en", "Example", map[string]any{"Name": "CountMen"}, 2)
if englishVersion != "CountMen have nothing" {
t.Errorf("Localizations didn't quite work like they should, found : %s expected : %s", englishVersion, "CountMen have nothing")
return
Expand Down
4 changes: 2 additions & 2 deletions migrator.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,12 +116,12 @@ func (m *migrator) applyNewMigrations(ctx context.Context) error {
}

// MigrateDatastore finds missing migrations and records them in the database
func (s *Service) MigrateDatastore(ctx context.Context, migrationsDirPath string, migrations ...interface{}) error {
func (s *Service) MigrateDatastore(ctx context.Context, migrationsDirPath string, migrations ...any) error {
if migrationsDirPath == "" {
migrationsDirPath = "./migrations/0001"
}

migrations = append([]interface{}{&Migration{}}, migrations...)
migrations = append([]any{&Migration{}}, migrations...)
// Migrate the schema
err := s.DB(ctx, false).AutoMigrate(migrations...)
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion queue.go
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ func (s *Service) AddPublisher(ctx context.Context, reference string, queueURL s
}

// Publish Queue method to write a new message into the queue pre initialized with the supplied reference
func (s *Service) Publish(ctx context.Context, reference string, payload interface{}) error {
func (s *Service) Publish(ctx context.Context, reference string, payload any) error {
var metadata map[string]string

authClaim := ClaimsFromContext(ctx)
Expand Down
4 changes: 2 additions & 2 deletions repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ func (repo *BaseRepository) GetByID(id string, result BaseModelI) error {
return repo.getReadDb().Preload(clause.Associations).First(result, "id = ?", id).Error
}

func (repo *BaseRepository) GetLastestBy(properties map[string]interface{}, result BaseModelI) error {
func (repo *BaseRepository) GetLastestBy(properties map[string]any, result BaseModelI) error {

db := repo.getReadDb()

Expand All @@ -60,7 +60,7 @@ func (repo *BaseRepository) GetLastestBy(properties map[string]interface{}, resu
return db.Last(result).Error
}

func (repo *BaseRepository) GetAllBy(properties map[string]interface{}, result []BaseModelI) error {
func (repo *BaseRepository) GetAllBy(properties map[string]any, result []BaseModelI) error {

db := repo.getReadDb()

Expand Down
8 changes: 4 additions & 4 deletions service.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ const ctxKeyService = contextKey("serviceKey")
// It is pushed and pulled from contexts to make it easy to pass around.
type Service struct {
name string
jwtClient map[string]interface{}
jwtClient map[string]any
jwtClientSecret string
version string
environment string
Expand All @@ -54,7 +54,7 @@ type Service struct {
poolWorkerCount int
poolCapacity int
pool *pond.WorkerPool
driver interface{}
driver any
grpcServer *grpc.Server
grpcServerEnableReflection bool
priListener net.Listener
Expand All @@ -70,7 +70,7 @@ type Service struct {
startup func(s *Service)
cleanup func(ctx context.Context)
eventRegistry map[string]EventI
configuration interface{}
configuration any
startOnce sync.Once
stopMutex sync.Mutex
}
Expand Down Expand Up @@ -152,7 +152,7 @@ func (s *Service) LogLevel() *logrus.Level {
}

// JwtClient gets the authenticated jwt client if configured at startup
func (s *Service) JwtClient() map[string]interface{} {
func (s *Service) JwtClient() map[string]any {
return s.jwtClient
}

Expand Down

0 comments on commit f311084

Please sign in to comment.