wood chen 8770d79bb8 feat(docker-compose, config, handler): enhance deployment configuration, add metrics support, and improve proxy handling
- Updated docker-compose.yml to include resource limits and health checks for the service.
- Modified go.mod and go.sum to include the new dependency on golang.org/x/time.
- Enhanced main.go to add new metrics routes for monitoring.
- Updated config.json to include metrics configuration with password and token expiry.
- Refactored internal/config to implement a ConfigManager for dynamic configuration loading.
- Improved internal/handler to utilize a shared HTTP client and added metrics tracking for requests.
2024-11-30 21:11:05 +08:00

63 lines
1.2 KiB
Go

package handler
import (
"crypto/rand"
"encoding/base64"
"sync"
"time"
)
type tokenInfo struct {
createdAt time.Time
expiresIn time.Duration
}
type authManager struct {
tokens sync.Map
}
func newAuthManager() *authManager {
am := &authManager{}
// 启动token清理goroutine
go am.cleanExpiredTokens()
return am
}
func (am *authManager) generateToken() string {
b := make([]byte, 32)
rand.Read(b)
return base64.URLEncoding.EncodeToString(b)
}
func (am *authManager) addToken(token string, expiry time.Duration) {
am.tokens.Store(token, tokenInfo{
createdAt: time.Now(),
expiresIn: expiry,
})
}
func (am *authManager) validateToken(token string) bool {
if info, ok := am.tokens.Load(token); ok {
tokenInfo := info.(tokenInfo)
if time.Since(tokenInfo.createdAt) < tokenInfo.expiresIn {
return true
}
am.tokens.Delete(token)
}
return false
}
func (am *authManager) cleanExpiredTokens() {
ticker := time.NewTicker(time.Hour)
for range ticker.C {
am.tokens.Range(func(key, value interface{}) bool {
token := key.(string)
info := value.(tokenInfo)
if time.Since(info.createdAt) >= info.expiresIn {
am.tokens.Delete(token)
}
return true
})
}
}