feat(clean): cleaning a bit
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
Matthieu 'JP' DERASSE 2023-08-10 19:34:50 +00:00
parent d880059980
commit becfc84505
Signed by: mderasse
GPG Key ID: 55141C777B16A705
4 changed files with 44 additions and 15 deletions

View File

@ -1,2 +0,0 @@
# Resp Common
Resp for Response is a extended error management system

View File

@ -1,2 +0,0 @@
# Vault Common
Contain code that allow to interact with an Hashicorp Vault

36
webserver/request.go Normal file
View File

@ -0,0 +1,36 @@
package webserver
import (
"net"
"net/http"
"strings"
)
// ipHeaders contain a list of common header used by different app to forward the real client IP.
var ipHeaders = []string{"CF-Connecting-IP", "True-Client-IP", "X-Client-IP", "X-Real-IP"}
// GetClientIP will check a http.Request and retrieve the real client IP.
func GetClientIP(r *http.Request) string {
for _, ipHeader := range ipHeaders {
if ip := r.Header.Get(ipHeader); ip != "" {
return ipHeader
}
}
if ips := r.Header.Get("X-Forwarded-For"); ips != "" {
i := strings.Index(ips, ",")
if i == -1 {
i = len(ips)
}
ip := ips[:i]
return strings.TrimSpace(ip)
}
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return ""
}
return host
}

View File

@ -4,13 +4,12 @@ import (
"context"
"errors"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"git.dev.m-and-m.ovh/mderasse/gocommon/commonctx"
)
const defaultTimeout = 90 * time.Second
@ -28,8 +27,6 @@ type ExecuteServerParams struct {
// and call the cleanup function.
func ExecuteServer(ctx context.Context, srv *http.Server, params *ExecuteServerParams) error {
log := commonctx.GetLogger(ctx)
if srv == nil {
return fmt.Errorf("missing http.server params")
}
@ -42,13 +39,13 @@ func ExecuteServer(ctx context.Context, srv *http.Server, params *ExecuteServerP
srv.WriteTimeout = defaultTimeout
}
log.Infof("launching webserver on %s", srv.Addr)
log.Printf("launching webserver on %s", srv.Addr)
go func() {
if err := srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
log.WithError(err).Fatalf("HTTP server error: %v", err)
log.Panicf("HTTP server error: %v", err)
}
log.Info("Stopped serving new connections.")
log.Printf("Stopped serving new connections.")
}()
sigChan := make(chan os.Signal, 1)
@ -59,17 +56,17 @@ func ExecuteServer(ctx context.Context, srv *http.Server, params *ExecuteServerP
defer shutdownRelease()
if err := srv.Shutdown(shutdownCtx); err != nil {
log.WithError(err).Warnf("HTTP shutdown error: %v", err)
log.Panicf("HTTP shutdown error: %v", err)
}
if params.Cleanup != nil {
if params != nil && params.Cleanup != nil {
if err := params.Cleanup(); err != nil {
log.WithError(err).Warnf("Impossible to cleanup correctly after shutdown. error : %v", err)
log.Printf("Impossible to cleanup correctly after shutdown. error : %v", err)
return nil
}
}
log.Info("Graceful shutdown complete.")
log.Print("Graceful shutdown complete.")
return nil
}