- 实现用户注册、登录、JWT令牌认证功能 - 集成Gin、GORM、Viper、Zap等框架 - 添加密码加密、数据库操作、中间件等完整功能 - 配置多环境支持、日志轮转、CORS处理 - 创建完整的项目结构和配置文件体系
47 lines
816 B
Go
47 lines
816 B
Go
package main
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
)
|
|
|
|
// 模拟一个可能很慢的操作
|
|
func slowOperation() (string, error) {
|
|
time.Sleep(3 * time.Second) // 假设真的很慢
|
|
return "slow result", nil
|
|
}
|
|
|
|
func doWithTimeout(timeout time.Duration) (string, error) {
|
|
resultCh := make(chan string, 1)
|
|
errCh := make(chan error, 1)
|
|
|
|
go func() {
|
|
res, err := slowOperation()
|
|
if err != nil {
|
|
errCh <- err
|
|
return
|
|
}
|
|
resultCh <- res
|
|
}()
|
|
|
|
select {
|
|
case res := <-resultCh:
|
|
return res, nil
|
|
case err := <-errCh:
|
|
return "", err
|
|
case <-time.After(timeout):
|
|
return "", errors.New("操作超时")
|
|
}
|
|
}
|
|
|
|
func main() {
|
|
fmt.Println("开始调用,最大等待 2 秒...")
|
|
res, err := doWithTimeout(2 * time.Second)
|
|
if err != nil {
|
|
fmt.Println("失败:", err)
|
|
return
|
|
}
|
|
fmt.Println("成功:", res)
|
|
}
|