diff --git a/pkg/api/http/config.go b/pkg/api/http/config.go index 1e869db1..59c3448a 100644 --- a/pkg/api/http/config.go +++ b/pkg/api/http/config.go @@ -1,28 +1,65 @@ package http import ( + "fmt" "time" + "github.com/cloudwego/hertz/pkg/common/config" + "github.com/cloudwego/hertz/pkg/app/server" "github.com/cloudwego/hertz/pkg/network/netpoll" ) type ServerConfig struct { - HostPort string + Host string `yaml:"host"` + Port int `yaml:"port"` + ReadTimeout *time.Duration `yaml:"read_timeout"` + WriteTimeout *time.Duration `yaml:"write_timeout"` + IdleTimeout *time.Duration `yaml:"idle_timeout"` + MaxRequestBodySize *int `yaml:"max_request_body_size"` } func DefaultServerConfig() *ServerConfig { + maxReqBodySize := 4 * 1024 * 1024 + readTimeout := 3 * time.Second + writeTimeout := 3 * time.Second + idleTimeout := 1 * time.Second + return &ServerConfig{ - HostPort: "127.0.0.1:9099", + Host: "127.0.0.1", + Port: 9099, + IdleTimeout: &idleTimeout, + ReadTimeout: &readTimeout, + WriteTimeout: &writeTimeout, + MaxRequestBodySize: &maxReqBodySize, } } +func (cfg *ServerConfig) Address() string { + return fmt.Sprintf("%s:%v", cfg.Host, cfg.Port) +} + func (cfg *ServerConfig) ToServer() *server.Hertz { - // TODO: do real server build based on provided config - return server.Default( - server.WithIdleTimeout(1*time.Second), - server.WithHostPorts(cfg.HostPort), - server.WithMaxRequestBodySize(20<<20), + serverOptions := []config.Option{ + server.WithHostPorts(cfg.Address()), server.WithTransport(netpoll.NewTransporter), - ) + } + + if cfg.IdleTimeout != nil { + serverOptions = append(serverOptions, server.WithIdleTimeout(*cfg.IdleTimeout)) + } + + if cfg.ReadTimeout != nil { + serverOptions = append(serverOptions, server.WithReadTimeout(*cfg.ReadTimeout)) + } + + if cfg.WriteTimeout != nil { + serverOptions = append(serverOptions, server.WithWriteTimeout(*cfg.WriteTimeout)) + } + + if cfg.MaxRequestBodySize != nil { + serverOptions = append(serverOptions, server.WithMaxRequestBodySize(*cfg.MaxRequestBodySize)) + } + + return server.Default(serverOptions...) } diff --git a/pkg/api/http/server.go b/pkg/api/http/server.go index fc274b91..f8a78d17 100644 --- a/pkg/api/http/server.go +++ b/pkg/api/http/server.go @@ -42,7 +42,7 @@ func (srv *Server) Run() error { defaultGroup.GET("/health/", HealthHandler) - schemaDocURL := swagger.URL(fmt.Sprintf("http://%v/v1/swagger/doc.json", srv.config.HostPort)) + schemaDocURL := swagger.URL(fmt.Sprintf("http://%v/v1/swagger/doc.json", srv.config.Address())) defaultGroup.GET("/swagger/*any", swagger.WrapHandler(swaggerFiles.Handler, schemaDocURL)) return srv.server.Run()