Can't use a method from another file in same package

-2

That is my server.go file where I define my server struct and its methods.

package main

import (
    "fmt"
    "log"
    "net/http"

    "github.com/gorilla/mux"
)

type FrontendServer struct {
    Router *mux.Router
}

func (f *FrontendServer) Run(addr string) {
    log.Fatal(http.ListenAndServe(addr, f.Router))
}

// func (f *FrontendServer) InitializeRoutes() {
//  f.Router.HandleFunc("/", f.handleHome)
// }

func (f *FrontendServer) HandleHome(w http.ResponseWriter, h *http.Request) {
    fmt.Fprintf(w, "sadsadas")
}

Here is my main.go file where I start my application.

package main

func main() {
    server := FrontendServer{}
    server.Router.HandleFunc("/", server.HandleHome)
    server.Run(":8080")
}

When I run the app with go run *.go it gives me the error below

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

goroutine 1 [running]:
github.com/gorilla/mux.(*Router).NewRoute(...)
        /Users/barisertas/go/pkg/mod/github.com/gorilla/mux@v1.8.0/mux.go:279
github.com/gorilla/mux.(*Router).HandleFunc(0x0, 0x1305508, 0x1, 0xc000012d20, 0xffffffff)
        /Users/barisertas/go/pkg/mod/github.com/gorilla/mux@v1.8.0/mux.go:300 +0x3a
main.main()
        /Users/barisertas/microservices-demo/frontend/main.go:5 +0x92
exit status 2

I made uppercase of first letter of the method and both files are in the same package. Is it because of the gorilla/mux itself? Because in the import scope it is underlied red saying could not import github.com/gorilla/mux no required module provides package

Here is my go.mod and go.sum files.

module github.com/bariis/microservices-demo/frontend

go 1.16

require github.com/gorilla/mux v1.8.0 // indirect

github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
go
pointers
module
package
asked on Stack Overflow May 16, 2021 by baris • edited May 16, 2021 by Flimzy

1 Answer

0

This line:

server := FrontendServer{}

Creates a variable server of type FrontendServer. FrontendServer is a struct, and all its fields will have their zero value. FrontendServer.Router is a pointer, so it will be nil. A nil Router is not functional, calling any of its methods may panic, just as you experienced.

Initialize it properly:

server := FrontendServer{
    Router: mux.NewRouter(),
}
answered on Stack Overflow May 16, 2021 by icza

User contributions licensed under CC BY-SA 3.0