-2

I am going through a course in udemy about testing in golang and they gave a project as an example. The main.go file is like this:

package main

import (
    "net/http"

    "github.com/go-chi/chi/v5"
    "github.com/go-chi/chi/v5/middleware"
)

type application struct {
}

func (a *application) routes() http.Handler {
    mux := chi.NewRouter()
    mux.Use(middleware.Recoverer)
    return mux
}

and at the same level i have a file called routes.go which is like this:

package main

import (
    "net/http"

    "github.com/go-chi/chi/v5"
    "github.com/go-chi/chi/v5/middleware"
)

func (a *application) routes() http.Handler {
    mux := chi.NewRouter()
    mux.Use(middleware.Recoverer)
    return mux
}

When I ran the program it gives me this error: ./main.go:13:13: app.routes undefined (type application has no field or method routes)

If I delete the routes.go file and put everything on the main.go it works, but I don't understand why this is happening because routes and main are on the same package. Could someone explain me why this is happening?

JBeloqui
  • 27
  • 5
  • "When I ran the program it gives me this error" what exactly is the command you're running? – erik258 Aug 11 '23 at 20:53
  • go run main.go @erik258 – JBeloqui Aug 11 '23 at 21:00
  • 1
    In general you should only use `go run` for trivial cases where all the code is in a single file. You can make `go run` work for your situation but it's better to get into the habit of using `go build` when compiling a program composed of multiple source files and packages. – Kurtis Rader Aug 13 '23 at 00:21

1 Answers1

2

go run main.go

You're explicitly including only main.go because you specified it in that command. Please read go.dev/doc/tutorial/getting-started it has a ton of useful info. go run . is a command that would run the main package without specifying all the files.

erik258
  • 14,701
  • 2
  • 25
  • 31