Study/Go
[Golang] DB 연결할 때, timeout 설정하기 (context)
나른한댕댕이🐶
2022. 9. 2. 11:35
728x90
반응형
# Context
Golang에서 Context는 작업 명세서와 같은 역할을 한다.
timeout 설정 또한 이 context 패키지를 사용하여 설정할 수 있다.
# WithTimeout
기본 명령어는 다음과 같이 사용할 수 있다.
context.WithTimeout(context.Background(), 20*time.Second)
- 코드에 적용하기
package main
import (
"context"
"fmt"
"time"
)
func main() {
db, err := sql.Open("mysql", "root:1111@tcp(127.0.0.1:3306/data")
if err != nil {
log.Fatal("DB Connection Error: ", err)
}
defer db.Close()
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
}
728x90
반응형