Skip to content

Commit

Permalink
#41: Exposed the basic HTTP server configs
Browse files Browse the repository at this point in the history
  • Loading branch information
roma-glushko committed Jan 21, 2024
1 parent d4e6c84 commit e1bceef
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 9 deletions.
53 changes: 45 additions & 8 deletions pkg/api/http/config.go
Original file line number Diff line number Diff line change
@@ -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...)
}
2 changes: 1 addition & 1 deletion pkg/api/http/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down

0 comments on commit e1bceef

Please sign in to comment.