Vani Polnedi
Vani Polnedi

Reputation: 605

dial tcp : socket: too many open files

I'm getting dial tcp : socket: too many open files error when i do load test.By setting ulimit its working fine but is there any other solution without setting ulimit?

Code:

package main
import (
 "fmt"
 "io"
 "io/ioutil"
 "encoding/json"
 "net/http"
 )

type Struct_Response struct {
    Meta struct {
        Requestid        string
    }
} 

var HttpClient = &http.Client{}

func main(){
    apiUrl := "http://example.com"
    JsonStr :="teststr"
    conn_token :="1233333333333"
    req, err := http.NewRequest("POST", apiUrl, bytes.NewBuffer(JsonStr))
    if err!=nil{ 
        fmt.Println(err)
    }
    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("requestid", "1234")
    req.Header.Set("Authorization", "Bearer "+conn_token)
    req.Header.Set("Connection", "close")

    resp, err := HttpClient.Do(req)
    req.Close=true
    if resp!=nil && resp.StatusCode==200 {
        body, _ := ioutil.ReadAll(resp.Body)
        var Responce Struct_Response
        err := json.Unmarshal([]byte(string(body)), &Responce)
        if err != nil {
            fmt.Println(err)
        }
        io.Copy(ioutil.Discard, resp.Body)
        resp.Body.Close()
    }
}

Thanks in advance.

Upvotes: 5

Views: 11644

Answers (1)

karmakaze
karmakaze

Reputation: 36134

Your problem may be that you're not cleanly closing connections which causes delays to be added before reusing TCP port client port numbers.

In your code example above, the response body is only consumed and closed when the status is 200. You should always consume/close the response body when present.

Upvotes: 2

Related Questions