Go compiler; go run commnad

I have a folder structure cmd/web/main.go and handler.go, routes.go are also present in the same level as main.go, all declared as package main.

main.go

package main
type WebApp struct {
	dbModel *models.UserModel
}

func main() {
	db, err := dbSetUp()
	if err != nil {
		log.Fatal(err)
	}
	app := &WebApp{
		dbModel: &models.UserModel{DB: db},
	}

	webServer := &http.Server{
		Addr:         ":5030",
		Handler:      app.Routes(),
		IdleTimeout:  time.Minute,
		ReadTimeout:  5 * time.Second,
		WriteTimeout: 10 * time.Second,
	}
	fmt.Println("server running...")
	err = webServer.ListenAndServe()
	log.Fatal(err)
}

routes.go

package main
func (a *WebApp) Routes() *http.ServeMux {

	mux := http.NewServeMux()

	mux.HandleFunc("/signup", a.Signup)

	return mux
}

go run cmd/web/main.go, compiler complains app.Routes undefiend (type *WebApp has no field or method Routes), but the go tools(formatter) does not complain such in the IDE.
If rearrange, putting the methods in the main.go file, all goes fine. When i research online, i found something similar suggesting it my improper use of go run command. what am i doing wrongly?. thanks.

The main package does not “consolidate” the files into a single package as it is done for other packages.

You want to either have all the code in a single file, or create a proper project and move the handler and routes to another package that you then import from the main package.

1 Like

Hi @Oluwatobi_Giwa,

Try go run cmd/web/main.go cmd/web/routes.go cmd/web/handler.go (or simply go cmd/web/*.go if it is ok to include all .go files in /cmd/web).

go run does not actively search for files; it only uses the files it receives as arguments.

1 Like

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