chrly/internal/di/server.go

58 lines
1.3 KiB
Go
Raw Normal View History

package di
import (
"errors"
"fmt"
"net/http"
"runtime/debug"
"time"
2023-12-13 21:59:12 +05:30
"github.com/defval/di"
"github.com/spf13/viper"
. "ely.by/chrly/internal/http"
"ely.by/chrly/internal/security"
)
var serverDiOptions = di.Options(
di.Provide(newAuthenticator, di.As(new(Authenticator))),
di.Provide(newServer),
)
func newAuthenticator(config *viper.Viper) (*security.Jwt, error) {
key := config.GetString("chrly.secret")
if key == "" {
return nil, errors.New("chrly.secret must be set in order to use authenticator")
}
return security.NewJwt([]byte(key)), nil
}
2024-02-14 05:26:48 +05:30
func newServer(Config *viper.Viper, Handler http.Handler) *http.Server {
Config.SetDefault("server.host", "")
Config.SetDefault("server.port", 80)
2024-02-14 05:26:48 +05:30
var handler http.Handler = http.HandlerFunc(func(request http.ResponseWriter, response *http.Request) {
defer func() {
if recovered := recover(); recovered != nil {
debug.PrintStack()
request.WriteHeader(http.StatusInternalServerError)
}
}()
2020-04-20 19:42:58 +05:30
2024-02-14 05:26:48 +05:30
Handler.ServeHTTP(request, response)
})
2020-04-20 19:42:58 +05:30
2024-02-14 05:26:48 +05:30
address := fmt.Sprintf("%s:%d", Config.GetString("server.host"), Config.GetInt("server.port"))
server := &http.Server{
Addr: address,
ReadTimeout: 5 * time.Second,
WriteTimeout: 5 * time.Second,
IdleTimeout: 60 * time.Second,
MaxHeaderBytes: 1 << 16,
Handler: handler,
}
return server
}