Skip to content

Instantly share code, notes, and snippets.

@muratsplat
Created February 25, 2016 21:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save muratsplat/88a283614a00c9ffe1b0 to your computer and use it in GitHub Desktop.
Save muratsplat/88a283614a00c9ffe1b0 to your computer and use it in GitHub Desktop.
Simple Web Server written in Golang
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()
}
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