Created
February 25, 2016 21:12
-
-
Save muratsplat/88a283614a00c9ffe1b0 to your computer and use it in GitHub Desktop.
Simple Web Server written in Golang
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" | |
"log" | |
"net/http" | |
"strings" | |
"time" | |
) | |
var numberOfPost int32 = 0 | |
var runtimes int = 1020 | |
var failed int = 0 | |
var success int = 0 | |
func main() { | |
respChan := make(chan int) | |
for i := 0; i < runtimes; i++ { | |
go Post(i, respChan) | |
} | |
go func() { | |
for { | |
statusCode := <-respChan | |
if statusCode == int(200) { | |
success++ | |
} else { | |
failed++ | |
} | |
log.Println("Success: ", success) | |
log.Println("Failed: ", failed) | |
} | |
}() | |
select {} | |
} | |
func Post(msg int, respCh chan int) { | |
json := `{"no":"%d"}` | |
reader := strings.NewReader(fmt.Sprintf(json, msg)) | |
client := &http.Client{} | |
client.Timeout = 60 * time.Second | |
req, err := http.NewRequest("POST", "http://localhost:8000/post", reader) | |
req.Header.Add("Content-type", "application/json") | |
if err != nil { | |
panic(err) | |
} | |
resp, err := client.Do(req) | |
if err != nil { | |
panic(err) | |
} | |
respCh <- resp.StatusCode | |
defer resp.Body.Close() | |
} |
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 ( | |
"io/ioutil" | |
"log" | |
"net/http" | |
"time" | |
) | |
var numberOfRequest = 0 | |
func main() { | |
http.HandleFunc("/post", Index) | |
http.ListenAndServe("localhost:8000", nil) | |
} | |
func Index(w http.ResponseWriter, r *http.Request) { | |
rBody, err := ioutil.ReadAll(r.Body) | |
if err != nil { | |
panic(err) | |
} | |
time.Sleep(time.Second * 4) | |
log.Println(string(rBody)) | |
numberOfRequest++ | |
log.Println(numberOfRequest) | |
defer r.Body.Close() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment