How to read StatusCode from req.Response.StatusCode

I am getting an error:

invalid memory address or nil pointer dereference

my code looks like:

func (ctr *Controller) Login(c *common.CPContext, req *http.Request, res http.ResponseWriter) (int, interface{}) {

	defer func() {
		var code = req.Response.StatusCode;  // error is here!!

		log.Error(code)
		if code < 400 {
			user.LoginAttempts = 0
		} else {
			user.LoginAttempts = user.LoginAttempts + 1
		}
		_, err := user.Update(ctx, db, boil.Infer())
		if err != nil {
			log.Warningf("could not save/update user model: %v", err)
		}

	}()
   // ...
}

how do I handle the pointer situation here? I just want to get the http.Response and the http.Response.StatusCode specifically here…

My guess is that req is cleaned up when you enter the deferred func. Try passing req to your func, and see if that solves your issue :slight_smile:

By the time your defered func is called everything is ‘gone’

Take a look at https://github.com/thoas/stats/blob/master/stats.go, which does what you are trying to do. they use http.Hijacker within their recorder

Hi, this could be helpful also: https://github.com/Erilbeth/gocheck

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.