Created
April 16, 2016 18:17
-
-
Save sgade/2a9ad99129b52f9e0fb7d69c9d6497e5 to your computer and use it in GitHub Desktop.
Golang streaming (http) client
This file contains 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" | |
"io" | |
"net" | |
"time" | |
) | |
const ( | |
addr = "localhost:3000" | |
maxConcurrentConnections = 100 | |
) | |
func sendRequest() { | |
con, err := net.Dial("tcp", addr) | |
if err != nil { | |
fmt.Printf("Could not connect to %q: %v.", addr, err) | |
} | |
// this is needed for HTTP Servers to respond at all | |
fmt.Fprintf(con, "GET / HTTP/1.0\r\n\r\n") | |
buffer := make([]byte, 10) | |
err = nil | |
for { | |
read, err := con.Read(buffer) | |
if read > 0 { | |
fmt.Printf(string(buffer[:read])) | |
} | |
if err != nil { | |
if err == io.EOF { | |
break | |
} | |
fmt.Printf("Error reading: %v.", err) | |
} | |
} | |
} | |
func sendRequests(abort <-chan time.Time) { | |
requestDone := make(chan bool) | |
currentRequests := 0 | |
for { | |
select { | |
case <-abort: | |
return | |
case <-requestDone: | |
currentRequests-- | |
default: | |
if currentRequests < maxConcurrentConnections { | |
currentRequests++ | |
go func(requestDone chan bool) { | |
sendRequest() | |
requestDone <- true | |
}(requestDone) | |
} | |
} | |
} | |
} | |
func main() { | |
duration := time.After(10 * time.Second) | |
go sendRequests(duration) | |
<-duration | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment