'Refactor main.go to another packages
Good, first of all, I am learning Go and I am a deaf person and English is not my main language.
I'm having a hard time understanding the videos, even though they are subtitled, I don't understand very well many times. Even so, I really want to learn.
I want to understand why methods in the same package (main) works, ex.:
main.go
type application struct {
config config
logger *log.Logger
}
routes.go
func (app *application) routes() *httprouter.Router {
router := httprouter.New()
router.HandlerFunc(http.MethodGet, "/status", app.statusHandler)
return router
}
then I refactor like this:
main.go
app := &config.Application{
Config: cfg,
Logger: logger,
}
config.go
type Application struct {
Config Config
Logger *log.Logger
}
routes.go
func (app *config.Application) Routes() *httprouter.Router {
router := httprouter.New()
router.HandlerFunc(http.MethodGet, "/status", app.statusHandler)
return router
}
statusHandler.go
func (app *config.Application) StatusHandler(w http.ResponseWriter, r *http.Request) {
currentStatus := config.AppStatus{
Status: "OK",
Environment: app.Config.Env,
Version: app.Config.Version,
}
js, err := json.MarshalIndent(currentStatus, "", "\t")
if err != nil {
app.Logger.Println(err)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(js)
}
But app are underlined and say me: invalid receiver type *config.Application.
I would be glad if someone can explain me the problem and how to fix this and make it multi-module with methods or other accepted way.
Regards, Pedro.
I have tried to do it with another new project, doing it step by step in case I missed something. However, I realized that I don't seem to be very clear on the concept of methods.
Solution 1:[1]
I recomend you following the golang tour.
As explained here go code is made by packages, usually each folder represents its own package.
As answerd by Burak you can't create Methods outside the package that declare the type that they implement.
That said if you do something like this:
- baseFolder
|- main
|-- main.go (package main)
|- config
|-- config.go (package config)
|-- routes.go (package config)
|-- statusHandler.go (package config)
You can use your code without referencing the "package"
func (app *Application) StatusHandler(w http.ResponseWriter, r *http.Request) {
...}
And import it on your main.go
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Felipe Colussi-oliva |
