fix api
This commit is contained in:
parent
01b8951dd5
commit
10ebc59ffb
17 changed files with 1087 additions and 238 deletions
34
utils/http.go
Normal file
34
utils/http.go
Normal file
|
@ -0,0 +1,34 @@
|
|||
package utils
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// SendErrorResponse 发送错误响应
|
||||
func SendErrorResponse(w http.ResponseWriter, message string, status int) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"success": false,
|
||||
"message": message,
|
||||
})
|
||||
}
|
||||
|
||||
// SendJSONResponse 发送JSON响应
|
||||
func SendJSONResponse(w http.ResponseWriter, data interface{}, status ...int) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
// 默认状态码为200 OK
|
||||
statusCode := http.StatusOK
|
||||
if len(status) > 0 {
|
||||
statusCode = status[0]
|
||||
}
|
||||
|
||||
w.WriteHeader(statusCode)
|
||||
if err := json.NewEncoder(w).Encode(data); err != nil {
|
||||
log.Printf("Error encoding response: %v", err)
|
||||
SendErrorResponse(w, "Internal server error", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
57
utils/validation.go
Normal file
57
utils/validation.go
Normal file
|
@ -0,0 +1,57 @@
|
|||
package utils
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// ParseInt64 将字符串解析为int64类型
|
||||
func ParseInt64(s string) (int64, error) {
|
||||
return strconv.ParseInt(s, 10, 64)
|
||||
}
|
||||
|
||||
// ValidateToken 验证令牌数据的有效性
|
||||
func ValidateToken(id, issuer, account, secret, tokenType, algo string, counter, period, digits int) error {
|
||||
if id == "" {
|
||||
return errors.New("token ID is required")
|
||||
}
|
||||
if issuer == "" {
|
||||
return errors.New("issuer is required")
|
||||
}
|
||||
if account == "" {
|
||||
return errors.New("account is required")
|
||||
}
|
||||
if secret == "" {
|
||||
return errors.New("secret is required")
|
||||
}
|
||||
|
||||
// 验证令牌类型
|
||||
if tokenType != "totp" && tokenType != "hotp" {
|
||||
return errors.New("invalid token type: must be 'totp' or 'hotp'")
|
||||
}
|
||||
|
||||
// 验证HOTP计数器
|
||||
if tokenType == "hotp" && counter < 0 {
|
||||
return errors.New("counter must be non-negative for HOTP tokens")
|
||||
}
|
||||
|
||||
// 验证周期
|
||||
if period <= 0 {
|
||||
return errors.New("period must be positive")
|
||||
}
|
||||
|
||||
// 验证位数
|
||||
if digits < 6 || digits > 8 {
|
||||
return errors.New("digits must be between 6 and 8")
|
||||
}
|
||||
|
||||
// 验证算法
|
||||
switch algo {
|
||||
case "SHA1", "SHA256", "SHA512":
|
||||
// 有效的算法
|
||||
default:
|
||||
return errors.New("invalid algorithm: must be SHA1, SHA256, or SHA512")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue