0

I realized that when building a web server, all of the routes and functions that handle them are in the main.go file. As the application grows, I imagine it could be hard to keep track of everything.

Is there a convention regarding "storing" the routes and handler functions in a file other than main.go?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Gambit2007
  • 3,260
  • 13
  • 46
  • 86
  • You can have any number of files in your main package. I suggest you start with the documentation and see how packages work, which will probably provide a lot of insight into how you can modularize your code. – JimB Oct 30 '19 at 23:21

1 Answers1

1

Here is how I do it. Say you have a ping handler which checks a database connection, and you have it in a package named your/app/animal:

package animal

...

func Ping(db *sql.DB) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        if err := db.PingContext(context.TODO()); err != nil {
            http.Error(w, err, http.StatusInternalServerError)
        }
    })
}

You can set it up like:

package main

...

func main() {
   db, _ := sql.Open("foo",os.GetEnv("DB"))
   http.Handle("/ping",animal.Ping(db))
   log.Fatal(http.ListenAndServe(os.GetEnv("BIND"),nil)
}
Markus W Mahlberg
  • 19,711
  • 6
  • 65
  • 89