- 필수 기능
- 시작하기
- Glossary
- 표준 속성
- Guides
- Agent
- 통합
- 개방형텔레메트리
- 개발자
- API
- Datadog Mobile App
- CoScreen
- Cloudcraft
- 앱 내
- 서비스 관리
- 인프라스트럭처
- 애플리케이션 성능
- APM
- Continuous Profiler
- 스팬 시각화
- 데이터 스트림 모니터링
- 데이터 작업 모니터링
- 디지털 경험
- 소프트웨어 제공
- 보안
- AI Observability
- 로그 관리
- 관리
ID: go-security/http-support-timeout
Language: Go
Severity: Notice
Category: Security
CWE: 400
When using an HTTP server in Go, it is highly recommended to define a timeout to handle and control the maximum duration of requests. Failing to set a timeout can lead to various issues, including:
To set a timeout in an HTTP server using the http.Server
package in Go, you can use the ReadTimeout
and WriteTimeout
fields of the Server
struct. These fields control the maximum duration for reading the entire request and writing the entire response, respectively. For example:
package main
import (
"net/http"
"time"
)
func main() {
server := &http.Server{
Addr: ":8080",
ReadTimeout: 5 * time.Second, // Set read timeout to 5 seconds
WriteTimeout: 10 * time.Second, // Set write timeout to 10 seconds
}
err := server.ListenAndServe()
if err != nil {
// handle error
}
}
In this example, the server is configured with a read timeout of 5 seconds and a write timeout of 10 seconds. Adjust these values according to the expected response times and the requirements of your application.
By defining appropriate timeouts, you can protect your server from DoS attacks, prevent resource congestion, improve user experience, and ensure the efficient utilization of server resources. It is a best practice to always include timeouts when working with HTTP servers in Go.
package main
import (
"log"
"net/http"
)
func main() {
s := http.Server{
Addr: fmt.Sprintf(":%s", config.Cfg.Webport),
Handler: router,
}
otherServer := http.Server{
Addr: fmt.Sprintf(":%s", config.Cfg.Webport),
Handler: router,
ReadTimeout: 10 * time.Second,
}
}
package main
import (
"log"
"net"
"net/http"
)
func main() {
l, err := net.Listen("tcp", ":8443")
if err != nil {
log.Fatal(err)
}
defer l.Close()
err = http.ServeTLS(l, nil, "cert.pem", "key.pem")
log.Fatal(err)
}
package main
import (
"log"
"net"
"net/http"
)
func main() {
l, err := net.Listen("tcp", ":8080")
if err != nil {
log.Fatal(err)
}
defer l.Close()
err = http.Serve(l, nil)
log.Fatal(err)
}
package main
import (
"log"
"net/http"
)
func main() {
err := http.ListenAndServeTLS(":8443", "cert.pem", "key.pem", nil)
log.Fatal(err)
}
package main
import (
"log"
"net/http"
)
func main() {
err := http.ListenAndServe(":8080", nil)
log.Fatal(err)
}
package main
import (
"log"
"net"
"net/http"
)
func main() {
server := &http.Server{
Addr: ":8443",
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 10 * time.Second,
}
err := server.ListenAndServe()
if err != nil {
log.Fatal(err)
}
}