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


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

package main

import (


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)

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]:*Router).NewRoute(...)
        /Users/barisertas/go/pkg/mod/*Router).HandleFunc(0x0, 0x1305508, 0x1, 0xc000012d20, 0xffffffff)
        /Users/barisertas/go/pkg/mod/ +0x3a
        /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 no required module provides package

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


go 1.16

require v1.8.0 // indirect v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI= v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
asked on Stack Overflow May 16, 2021 by baris • edited May 16, 2021 by Flimzy

1 Answer


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