Last active
December 19, 2021 11:39
-
-
Save lotusirous/d02219ff21f6fe9b4e5b7004fd62c027 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 ( | |
| "log" | |
| "net/http" | |
| "sync/atomic" | |
| "time" | |
| ) | |
| var isBusy int32 | |
| const ( | |
| // FREE is the status that server is free | |
| FREE = 0 | |
| // BUSY is the status that server is busy | |
| BUSY = 1 | |
| ) | |
| func HandleSync() http.HandlerFunc { | |
| return func(w http.ResponseWriter, r *http.Request) { | |
| status := atomic.LoadInt32(&isBusy) | |
| ctx := r.Context() | |
| if status == FREE { | |
| atomic.StoreInt32(&isBusy, 1) | |
| defer func() { | |
| atomic.StoreInt32(&isBusy, 0) | |
| }() | |
| select { | |
| case <-time.After(10 * time.Second): | |
| w.WriteHeader(200) | |
| w.Write([]byte(`Working...`)) | |
| case <-ctx.Done(): | |
| err := ctx.Err() | |
| log.Println("context is fired: ", err) | |
| http.Error(w, err.Error(), http.StatusInternalServerError) | |
| return | |
| } | |
| } | |
| if status == BUSY { | |
| w.WriteHeader(http.StatusForbidden) | |
| w.Write([]byte(`I'm busy`)) | |
| } | |
| } | |
| } | |
| func main() { | |
| addr := ":1234" | |
| r := http.NewServeMux() | |
| r.Handle("/", HandleSync()) | |
| svr := &http.Server{ | |
| Addr: addr, | |
| Handler: r, | |
| } | |
| log.Println("server started", addr) | |
| log.Fatal(svr.ListenAndServe()) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment