Created
May 11, 2023 09:23
-
-
Save Apurer/a31f66ca72d0f03fd1302b08c85c4353 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"net" | |
"net/http" | |
"sync" | |
"time" | |
) | |
type UserTask struct { | |
mtx1 sync.Mutex | |
mtx2 sync.Mutex | |
isNew bool | |
} | |
var ( | |
userTaskMap map[string]*UserTask | |
mapMtx sync.Mutex | |
) | |
func main() { | |
userTaskMap = make(map[string]*UserTask) | |
http.HandleFunc("/", handleRequest) | |
fmt.Println("Starting server on :8080") | |
http.ListenAndServe(":8080", nil) | |
} | |
func handleRequest(w http.ResponseWriter, r *http.Request) { | |
ip, _, err := net.SplitHostPort(r.RemoteAddr) | |
if err != nil { | |
http.Error(w, "Error parsing IP address", http.StatusInternalServerError) | |
return | |
} | |
mapMtx.Lock() | |
task, ok := userTaskMap[ip] | |
if !ok { | |
task = &UserTask{ | |
isNew: true, | |
} | |
userTaskMap[ip] = task | |
} | |
mapMtx.Unlock() | |
task.mtx1.Lock() | |
task.isNew = true | |
task.mtx2.Unlock() | |
go func() { | |
time.Sleep(1 * time.Second) | |
task.mtx2.Lock() | |
task.isNew = false | |
task.mtx1.Unlock() | |
}() | |
task.mtx2.Lock() | |
if task.isNew { | |
task.mtx1.Unlock() | |
fmt.Fprintf(w, "Skipping request from %s\n", ip) | |
return | |
} | |
longRunningTask(task) | |
fmt.Fprintf(w, "Task completed for IP: %s\n", ip) | |
} | |
func longRunningTask(task *UserTask) { | |
task.mtx2.Unlock() | |
time.Sleep(5 * time.Second) | |
task.mtx2.Lock() | |
task.mtx2.Unlock() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment