refactor: changed file structure
This commit is contained in:
12
pkg/contexts/keys.go
Normal file
12
pkg/contexts/keys.go
Normal file
@@ -0,0 +1,12 @@
|
||||
package contexts
|
||||
|
||||
type contextKey string
|
||||
|
||||
func (c contextKey) String() string {
|
||||
return "projectreshoot context key " + string(c)
|
||||
}
|
||||
|
||||
var (
|
||||
contextKeyAuthorizedUser = contextKey("auth-user")
|
||||
contextKeyRequestTime = contextKey("req-time")
|
||||
)
|
||||
21
pkg/contexts/request_timer.go
Normal file
21
pkg/contexts/request_timer.go
Normal file
@@ -0,0 +1,21 @@
|
||||
package contexts
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Set the start time of the request
|
||||
func SetStart(ctx context.Context, time time.Time) context.Context {
|
||||
return context.WithValue(ctx, contextKeyRequestTime, time)
|
||||
}
|
||||
|
||||
// Get the start time of the request
|
||||
func GetStartTime(ctx context.Context) (time.Time, error) {
|
||||
start, ok := ctx.Value(contextKeyRequestTime).(time.Time)
|
||||
if !ok {
|
||||
return time.Time{}, errors.New("Failed to get start time of request")
|
||||
}
|
||||
return start, nil
|
||||
}
|
||||
25
pkg/contexts/user.go
Normal file
25
pkg/contexts/user.go
Normal file
@@ -0,0 +1,25 @@
|
||||
package contexts
|
||||
|
||||
import (
|
||||
"context"
|
||||
"projectreshoot/internal/models"
|
||||
)
|
||||
|
||||
type AuthenticatedUser struct {
|
||||
*models.User
|
||||
Fresh int64
|
||||
}
|
||||
|
||||
// Return a new context with the user added in
|
||||
func SetUser(ctx context.Context, u *AuthenticatedUser) context.Context {
|
||||
return context.WithValue(ctx, contextKeyAuthorizedUser, u)
|
||||
}
|
||||
|
||||
// Retrieve a user from the given context. Returns nil if not set
|
||||
func GetUser(ctx context.Context) *AuthenticatedUser {
|
||||
user, ok := ctx.Value(contextKeyAuthorizedUser).(*AuthenticatedUser)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return user
|
||||
}
|
||||
Reference in New Issue
Block a user