오늘도 한 뼘 더
[Golang] DB 연결할 때, timeout 설정하기 (context) 본문
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
반응형
'Study > Go' 카테고리의 다른 글
[Golang] AWS SNS(Simple Notification Service) 주제 리스트 조회하기 (0) | 2022.09.06 |
---|---|
[Golang] net/http 패키지로 API 호출하기 (0) | 2022.09.03 |
[Golang] Go 환경변수 쓰기/ 읽기 (0) | 2022.08.31 |
[Golang] .env 사용하여 환경변수 설정 (0) | 2022.08.30 |
[Golang] sql: unknown driver "mysql" (forgotten import?) 에러 해결하기 (0) | 2022.08.27 |
Comments