简体   繁体   中英

Golang how can I stop an Http request from continuing to fire

I was doing some load testing earlier today and found something peculiar, sometimes an Http request doesn't not die and keeps on firing . How can I correct that in my Golang code for instance see the image below . I am load testing loading 1,000 HTTP request but if you notice on the 1,000th request below it takes 392,999 milliseconds or 392 seconds while the rest of the request takes 2.2 seconds on average . I have done the test multiple times and sometimes it hangs . This is my code

func Home_streams(w http.ResponseWriter, r *http.Request) {
    var result string

    r.ParseForm()

    wg := sync.WaitGroup{}

    wg.Add(1)
    go func() {


    defer wg.Done()

    db.QueryRow("select json_build_object('Locations', array_to_json(array_agg(t))) from (SELECT latitudes,county,longitudes,"+
        "statelong,thirtylatmin,thirtylatmax,thirtylonmin,thirtylonmax,city"+
        " FROM zips where city='Orlando' ORDER BY city limit 5) t").Scan(&result)

    }()
    wg.Wait()

    fmt.Fprintf(w,result)
}

and I connect to the database with this code

func init() {
    var err error
    db, err = sql.Open("postgres","Postgres Connection String")

    if err != nil {
        log.Fatal("Invalid DB config:", err)
    }
    if err = db.Ping(); err != nil {
        log.Fatal("DB unreachable:", err)
    }
}

I would say that about 10 % of the time I load test this issue happens and the only way it stops is if I stop the requests manually otherwise it keeps on going indefinitely . I wonder if maybe this issue is addressed here https://medium.com/@nate510/don-t-use-go-s-default-http-client-4804cb19f779#.83uzpsp24 I am still learning my way around Golang . 在此处输入图片说明

and the only way it stops is if I stop the requests manually otherwise it keeps on going indefinitely

You're not showing your full code, but it seems like you're using the http.ListenAndServe convenience function, which doesn't set a default timeout. So what I assume is happening is you're overloading your database server and your http server isn't set to timeout so it's just waiting for your database to respond.

Assuming all of this is correct try doing something like this instead:

srv := &http.Server{  
    ReadTimeout: 5 * time.Second,
    WriteTimeout: 10 * time.Second,
}
srv.ListenAndServe()

There's a nice reference here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM