2020-04-19 05:01:09 +05:30
|
|
|
package di
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
2021-02-26 07:15:45 +05:30
|
|
|
"runtime/debug"
|
2020-04-19 05:01:09 +05:30
|
|
|
"time"
|
|
|
|
|
2023-12-13 21:59:12 +05:30
|
|
|
"github.com/defval/di"
|
2020-04-19 05:01:09 +05:30
|
|
|
"github.com/spf13/viper"
|
|
|
|
|
2024-02-01 12:42:34 +05:30
|
|
|
. "ely.by/chrly/internal/http"
|
2024-02-01 16:41:39 +05:30
|
|
|
"ely.by/chrly/internal/security"
|
2020-04-19 05:01:09 +05:30
|
|
|
)
|
|
|
|
|
2024-02-07 22:04:57 +05:30
|
|
|
var serverDiOptions = di.Options(
|
2020-04-19 05:01:09 +05:30
|
|
|
di.Provide(newAuthenticator, di.As(new(Authenticator))),
|
|
|
|
di.Provide(newServer),
|
|
|
|
)
|
|
|
|
|
2024-02-01 16:41:39 +05:30
|
|
|
func newAuthenticator(config *viper.Viper) (*security.Jwt, error) {
|
2020-04-19 05:01:09 +05:30
|
|
|
key := config.GetString("chrly.secret")
|
|
|
|
if key == "" {
|
|
|
|
return nil, errors.New("chrly.secret must be set in order to use authenticator")
|
|
|
|
}
|
|
|
|
|
2024-02-01 16:41:39 +05:30
|
|
|
return security.NewJwt([]byte(key)), nil
|
2020-04-19 05:01:09 +05:30
|
|
|
}
|
|
|
|
|
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)
|
2020-04-19 05:01:09 +05:30
|
|
|
|
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"))
|
2020-04-19 05:01:09 +05:30
|
|
|
server := &http.Server{
|
|
|
|
Addr: address,
|
|
|
|
ReadTimeout: 5 * time.Second,
|
|
|
|
WriteTimeout: 5 * time.Second,
|
|
|
|
IdleTimeout: 60 * time.Second,
|
|
|
|
MaxHeaderBytes: 1 << 16,
|
|
|
|
Handler: handler,
|
|
|
|
}
|
|
|
|
|
|
|
|
return server
|
|
|
|
}
|