Created
December 9, 2020 14:14
-
-
Save AVoskoboinikov/a8614e243f1e28b7d14dc871b86e52a7 to your computer and use it in GitHub Desktop.
golang: memory increases when server does not read requests' body
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/ioutil" | |
"net/http" | |
"runtime" | |
"strings" | |
"time" | |
) | |
var serverURL = "http://localhost:4040" | |
func main() { | |
monitorRuntime() | |
for { | |
sendHTTPRequest(buildHTTPRequest(), getHTTPClient()) | |
time.Sleep(10 * time.Millisecond) | |
} | |
} | |
func buildHTTPRequest() (*http.Request) { | |
data := strings.Repeat("x", 1048576) // 1048576 -> 1MB | |
req, err := http.NewRequest(http.MethodPost, serverURL, strings.NewReader(data)) | |
if err != nil { | |
panic(fmt.Sprintf("failed to build HTTP request: %v", err)) | |
} | |
req.Close = true | |
return req | |
} | |
func sendHTTPRequest(req *http.Request, cli *http.Client) { | |
resp, err := cli.Do(req) | |
if err != nil { | |
// write tcp [::1]:54091->[::1]:4040: write: protocol wrong type for socket | |
// write tcp [::1]:54096->[::1]:4040: write: broken pipe | |
return | |
} | |
defer resp.Body.Close() | |
_, _ = ioutil.ReadAll(resp.Body) | |
} | |
func getHTTPClient() *http.Client { | |
c := http.DefaultClient | |
return c | |
} | |
func monitorRuntime() { | |
go func() { | |
for { | |
var m runtime.MemStats | |
runtime.ReadMemStats(&m) | |
fmt.Println( | |
fmt.Sprintf( | |
"memo-sys-mb: %5v \t\t heap-inuse-mb: %5v \t\t heap-objects: %5v", | |
bToMb(m.Sys), | |
bToMb(m.HeapInuse), | |
m.HeapObjects, | |
), | |
) | |
time.Sleep(5 * time.Second) | |
} | |
}() | |
} | |
func bToMb(b uint64) uint64 { | |
return b / 1024 / 1024 | |
} |
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" | |
"log" | |
"net/http" | |
) | |
func handler(w http.ResponseWriter, r *http.Request) { | |
w.WriteHeader(http.StatusOK) | |
fmt.Fprintf(w, "{\"jsonrpc\": \"2.0\", \"error\": {\"code\": -32000, \"message\": \"Something went wrong...\"}, \"id\": \"1\"}") | |
} | |
func main() { | |
http.HandleFunc("/", handler) | |
log.Fatal(http.ListenAndServe(":4040", nil)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment