diff --git a/main.go b/main.go index 3a05a31..2953566 100644 --- a/main.go +++ b/main.go @@ -21,23 +21,27 @@ import ( "database/sql" "flag" "fmt" - "github.com/timewarrior-synchronize/timew-sync-server/storage" - "github.com/timewarrior-synchronize/timew-sync-server/sync" "log" "net/http" "os" + "time" + + "github.com/timewarrior-synchronize/timew-sync-server/storage" + "github.com/timewarrior-synchronize/timew-sync-server/sync" _ "github.com/mattn/go-sqlite3" ) -var versionFlag bool -var configFilePath string -var portNumber int -var keyDirectoryPath string -var dbPath string -var noAuth bool -var sourcePath string -var userID int64 +var ( + versionFlag bool + configFilePath string + portNumber int + keyDirectoryPath string + dbPath string + noAuth bool + sourcePath string + userID int64 +) func main() { startCmd := flag.NewFlagSet("start", flag.ExitOnError) @@ -99,14 +103,21 @@ func main() { sync.HandleSyncRequest(w, req, noAuth) } healthHandler := func(w http.ResponseWriter, req *http.Request) { - fmt.Fprint(w, "OK") + fmt.Fprint(w, "OK") } http.HandleFunc("/api/sync", syncHandler) http.HandleFunc("/api/health", healthHandler) log.Printf("Listening on Port %v", portNumber) - log.Fatal(http.ListenAndServe(fmt.Sprintf(":%v", portNumber), nil)) + srv := &http.Server{ + Addr: fmt.Sprintf(":%v", portNumber), + ReadHeaderTimeout: 10 * time.Second, + ReadTimeout: 30 * time.Second, + WriteTimeout: 60 * time.Second, + IdleTimeout: 120 * time.Second, + } + log.Fatal(srv.ListenAndServe()) } // Subcommand for adding a new user diff --git a/sync/handle.go b/sync/handle.go index d5b798f..6fdac2d 100644 --- a/sync/handle.go +++ b/sync/handle.go @@ -32,6 +32,11 @@ var PublicKeyLocation string // HandleSyncRequest receives sync requests and starts the sync // process with the received data. func HandleSyncRequest(w http.ResponseWriter, req *http.Request, noAuth bool) { + if req.Method != http.MethodPost { + http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) + return + } + requestBody, err := io.ReadAll(req.Body) if err != nil { log.Printf("Error reading HTTP request, ignoring request: %v", err) diff --git a/sync/user_management.go b/sync/user_management.go index 7a226bf..42ccee0 100644 --- a/sync/user_management.go +++ b/sync/user_management.go @@ -95,7 +95,6 @@ func AddKey(userID int64, key string) { key = "\n" + key } if _, err = destFile.WriteString(key); err != nil { - destFile.Close() log.Fatalf("Error adding key. Unable to write to key file with user id %v", userID) } }