Improve http action notification

Send the notification using a goroutine and set the request timeout to 15 seconds
This commit is contained in:
Nicola Murino 2019-07-27 19:29:33 +02:00
parent c4fbca9ea2
commit 4a46b84dd5

View file

@ -3,6 +3,7 @@ package sftpd
import ( import (
"fmt" "fmt"
"net/http" "net/http"
"net/url"
"os" "os"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
@ -304,24 +305,31 @@ func executeAction(operation string, username string, path string, target string
} }
} }
if len(actions.HTTPNotificationURL) > 0 { if len(actions.HTTPNotificationURL) > 0 {
var req *http.Request var url *url.URL
req, err = http.NewRequest(http.MethodGet, actions.HTTPNotificationURL, nil) url, err = url.Parse(actions.HTTPNotificationURL)
if err == nil { if err == nil {
q := req.URL.Query() q := url.Query()
q.Add("action", operation) q.Add("action", operation)
q.Add("username", username) q.Add("username", username)
q.Add("path", path) q.Add("path", path)
if len(target) > 0 { if len(target) > 0 {
q.Add("target_path", target) q.Add("target_path", target)
} }
req.URL.RawQuery = q.Encode() url.RawQuery = q.Encode()
resp, err := http.DefaultClient.Do(req) go func() {
startTime := time.Now()
httpClient := &http.Client{
Timeout: 15 * time.Second,
}
resp, err := httpClient.Get(url.String())
respCode := 0 respCode := 0
if err == nil { if err == nil {
respCode = resp.StatusCode respCode = resp.StatusCode
resp.Body.Close() resp.Body.Close()
} }
logger.Debug(logSender, "notified action to URL: %v status code: %v err: %v", req.URL.RequestURI(), respCode, err) logger.Debug(logSender, "notified action to URL: %v status code: %v, elapsed: %v err: %v",
url.String(), respCode, time.Since(startTime), err)
}()
} else { } else {
logger.Warn(logSender, "Invalid http_notification_url \"%v\" : %v", actions.HTTPNotificationURL, err) logger.Warn(logSender, "Invalid http_notification_url \"%v\" : %v", actions.HTTPNotificationURL, err)
} }