0

I am trying to consolidate routing functionality within a web service. The package main has two files of concern, route.go and main.go.

Within route.go I am defining routing as follows:

package main

import (
    "github.com/justinas/alice"
    "net/http"
)

func (app *Application) Routes() http.Handler {
    standardMiddleware := alice.New(app.logRequest)

    mux := http.NewServeMux()
    mux.HandleFunc("/ping", helpers.Ping)

    return standardMiddleware.Then(mux)
}

Within main.go I am trying to execute the application as follows:

package main

import (
    "flag"
    "log"
    "net/http"
    "os"
)

type Application struct {
    errorLog *log.Logger
}

func main() {
    addr := flag.String("addr", ":8080", "HTTP Network Address")
    flag.Parse()

    errorLog := log.New(os.Stderr, "ERROR\t", log.Ldate|log.Ltime|log.Lshortfile)

    app := &Application{
        errorLog: errorLog,
    }

    srv := &http.Server{
        Addr:     *addr,
        ErrorLog: errorLog,
        Handler:  app.Routes(),
    }

    err := srv.ListenAndServe()
    errorLog.Fatal(err)
}

When I execute the program I get the following error: app.Routes undefined (type *Application has no field or method Routes)

I'm not sure why the method isn't registering correctly?

shbfy
  • 2,075
  • 3
  • 16
  • 37
  • How do you execute the program? – Sergio Tulentsev Aug 01 '19 at 10:45
  • It won't compile. I attempt to execute here: ` go run cmd/web/main.go ` Apologies where have I gone wrong? Thanks for your help :) – shbfy Aug 01 '19 at 10:46
  • Seems like your `Application` struct doesn't have `logRequest` field either – Kamol Hasan Aug 01 '19 at 11:07
  • I've defined that elsewhere, I can add if that would be helpful? It's not throwing an error for `logRequest` at the moment. – shbfy Aug 01 '19 at 11:23
  • 2
    `go run cmd/web/main.go` is your problem. That's now how `go run` should be used. Better to use `go build` or `go install` on the package path (or without any argument for the current directory). If for some reason you insist on using `go run`, with recent versions of Go you can use `go run .` to build and run the package in the current directory. – Dave C Aug 01 '19 at 12:12

1 Answers1

4

Try using:

go run cmd/web/main.go cmd/web/route.go 

go run takes file or files as input. It compiles only those file or files before running. So you need to add route.go file as input otherwise the method you declared in it, will be undefined.

go run ./cmd/web also works.

Update:

If you're in the same directory of main.go, just use:

go run .
Kamol Hasan
  • 12,218
  • 1
  • 37
  • 46