Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ahmedash95/702a3bec623b765a403aaca661c622a8 to your computer and use it in GitHub Desktop.
Save ahmedash95/702a3bec623b765a403aaca661c622a8 to your computer and use it in GitHub Desktop.
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
}
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