Pass pointer to variable to goroutine leads to nil values

I have the following issue in the Revel framework:
In my revel app i use revel modules. In one module is a function

func addToBlocklist(r *revel.Request, claims map[string]interface{})

which is called by

go addToBlocklist(c.Request, c.Args[jwt.TokenClaimsKey].(map[string]interface{}))

c is of type

type JwtAuth struct {
	*revel.Controller
}

reve.Controller’s Request is of type *revel.Request, just as expected by addToBlocklist.
When I fmt.Println(c.Request) before passing to addToBlocklist, it prints &{0xc0003079b0 0xc0003280b0 text/html html <nil> GET 127.0.0.1:35376 0.0.0.0:9001 /logout map[] <nil> 0xc0003265b0}
When I fmt.Println(r) in the first place of addToBlocklist, it prints &{<nil> 0xc0003280b0 <nil> <nil> map[] <nil> 0xc0003265b0}

This runs on docker machine with golang:1.14.6-alpine with revel test.

When I run it locally on go 1.14.6 windows the values of r in addToBlocklist are as they were passed.

The goroutine argument is evaluated and the goroutine is sent to the scheduler. Later, the goroutine is scheduled and executed, In between, the item referenced by the pointer argument is changed.

package main

import (
	"fmt"
	"time"
)

func main() {
	a := 42
	fmt.Println(a)
	go func(a *int) { fmt.Println(*a) }(&a)
	a = 7
	time.Sleep(10 * time.Millisecond)
}

https://play.golang.org/p/RBw64XoJPAN

42
7

You may also have a race condition. In which case, the results are undefined.

$ go run -race racer.go
42
==================
WARNING: DATA RACE
Read at 0x00c00013a010 by goroutine 7:
  main.main.func1()
      /home/petrus/racer.go:11 +0x3e

Previous write at 0x00c00013a010 by main goroutine:
  main.main()
      /home/petrus/racer.go:12 +0x112

Goroutine 7 (running) created at:
  main.main()
      /home/petrus/racer.go:11 +0x104
==================
7
Found 1 data race(s)
exit status 66
$

Please provide the code for a minimal, reproducible example of your issue.

Found out by adding defer fmt.Println© that the function, which is calling addToBlocklist, ends before addToBlocklist runs. And the Controller seems to be niled before addToBlocklist runs.

RefreshToken:  &{0xc00030b980 0xc000328080 text/html html   <nil> GET 127.0.0.1:35546 0.0.0.0:9001 /refresh-token map[] <nil> 0xc0002e4c30}
End RefreshToken:  &{0xc00030b980 0xc000328080 text/html html   <nil> GET 127.0.0.1:35546 0.0.0.0:9001 /refresh-token map[] <nil> 0xc0002e4c30}
addToBlockList:  &{<nil> 0xc000328080     <nil>    <nil> map[] <nil> 0xc0002e4c30}

Thnaks to @petrus for the hint

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