Last active
November 12, 2019 20:44
-
-
Save ahmedash95/702a3bec623b765a403aaca661c622a8 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 ( | |
"flag" | |
"fmt" | |
"net/http" | |
"time" | |
) | |
var port string | |
var limit chan int | |
func main() { | |
// initaite rate limit | |
limit = make(chan int, 10) | |
// service flags | |
flag.StringVar(&port, "port", "8000", "service http port") | |
flag.Parse() | |
// starting server | |
fmt.Printf("Starting server on :%s\n", port) | |
http.HandleFunc("/", handler) | |
http.ListenAndServe(fmt.Sprintf(":%s", port), nil) | |
} | |
func handler(w http.ResponseWriter, req *http.Request) { | |
limit <- 1 // push request if there is capacity, if not then wait | |
fmt.Println("Receiving a request") | |
time.Sleep(200 * time.Millisecond) | |
fmt.Fprintf(w, "hello\n") | |
// pull the request from the limiter | |
<-limit | |
} |
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 ( | |
"flag" | |
"fmt" | |
"net/http" | |
"time" | |
) | |
var port string | |
var limit chan int | |
func main() { | |
// initaite rate limit | |
limit = make(chan int, 10) | |
// service flags | |
flag.StringVar(&port, "port", "8000", "service http port") | |
flag.Parse() | |
// starting server | |
fmt.Printf("Starting server on :%s\n", port) | |
http.HandleFunc("/", handler) | |
http.ListenAndServe(fmt.Sprintf(":%s", port), nil) | |
} | |
func handler(w http.ResponseWriter, req *http.Request) { | |
// rate limit 10 concurrent | |
select { | |
case limit <- 1: // push request if there is capacity | |
default: // if not return server error | |
w.WriteHeader(http.StatusServiceUnavailable) | |
w.Write([]byte("503 - Maximum concurrent reatched!")) | |
return | |
} | |
fmt.Println("Receiving a request") | |
time.Sleep(200 * time.Millisecond) | |
fmt.Fprintf(w, "hello\n") | |
// pull the request from the limiter | |
<-limit | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment