diff --git a/api.go b/api.go index 588dd8c5dba12217508c7e0d854a8f19c66a0f21..8cae4aa45ef04841cdaf0b383e3345b29dd9a1ed 100644 --- a/api.go +++ b/api.go @@ -18,9 +18,13 @@ import ( "path/filepath" "strconv" "strings" + "sync" "syscall" + "time" ) +var m sync.Mutex + func main() { if _, err := os.Stat("/var/lib/image-viewer"); err != nil { @@ -86,9 +90,9 @@ func Stop(c echo.Context) error { } func Upload(c echo.Context) error { - //----------- - // Read file - //----------- + //protect ressources + m.Lock() + defer m.Unlock() // Source file, err := c.FormFile("file") @@ -139,6 +143,10 @@ func List(c echo.Context) error { } func Del(c echo.Context) error { + //protect ressources + m.Lock() + defer m.Unlock() + // Removing file from the directory // Using Remove() function img := c.Param("img") @@ -150,6 +158,9 @@ func Del(c echo.Context) error { } func Display(c echo.Context) error { + //protect ressources + m.Lock() + defer m.Unlock() //Check if program is running if _, err := os.Stat("/var/run/image-viewer.pid"); err != nil { @@ -187,6 +198,10 @@ func Display(c echo.Context) error { } syscall.Kill(pid, syscall.SIGUSR1) + //Ensure image has the time to be displayed before mutex release + //In case a subsequent call to display would be made before the signal is processed by the backend, + //the data from current.ppm could be corrupted (or too long) during process. + time.Sleep(500 * time.Millisecond) return c.String(http.StatusOK, img+" is being displayed\n") }