Openshift go-client api call panic out - "runtime error: invalid memory address or nil pointer dereference"

4.1k Views Asked by At

I am using a basic go code to verify the the route created in a namespace using OpenShift api module - https://github.com/openshift/api but it's panic out

$ cat route.go

package main

import (
    "context"
    "fmt"

    routev1 "github.com/openshift/api/route/v1"
    "k8s.io/apimachinery/pkg/types"
    "sigs.k8s.io/controller-runtime/pkg/client"
)

func main() {

    const (
        namespace = "test"
        routeName = "nodejs-basic"
    )

    var k8sClient client.Client

    route := &routev1.Route{}
    err := k8sClient.Get(context.TODO(), types.NamespacedName{Name: routeName, Namespace: namespace}, route)
    if err != nil {
        fmt.Println("Some issue")
    }
    fmt.Println("Api call completed")
}

Panic out while executing it

$ go run route.go

panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x10683e7]

goroutine 1 [running]:
main.main()
        /home/amit/go/src/github.com/amitkrout/usingopenshiftapi/route.go:22 +0x27
exit status 2

Any pointer ? What could be the reason and how to fix it ?

I have created a git repo - https://github.com/amitkrout/usingopenshiftapi. You can propose the fix in the repo too via pr

1

There are 1 best solutions below

0
On

You haven’t initialised k8sClient, so it’s nil, and calling k8sClient.Get() ultimately results in a nil pointer dereference.

One way to get a client is to use clientcmd; the documentation there shows how to go about it.