Search code examples
gohandlerhttpserver

Go doesn’t understand how the http.Server Handler calling functions which attached to an empty struct


I have this code of a simple web server, but I don’t understand this code:

Handler:app.routes(),

const webPort = "80"

type Config struct {}

func main() {

    app := Config{}
    log.Printf("Starting broker service on port %s\n",webPort)
    srv := &http.Server{
        Addr: fmt.Sprintf(":%s",webPort),
        Handler:app.routes(),
    }

    err := srv.ListenAndServe()
    if(err != nil) {
        log.Panic(err)
    }
}

And in the routes file:

func (app *Config) routes() http.Handler {
    mux := chi.NewRouter()
    mux.Use(cors.Handler(cors.Options{
        AllowedOrigins: []string{"http://*","https://*"},
        AllowedMethods: []string{"GET", "POST", "DELETE","PUT","OPTIONS"},
        AllowedHeaders: []string{"Accept","Authorization","Content-Type","X-CSRF-Token"},
        ExposedHeaders: []string{"Link"},
        AllowCredentials:true,
        MaxAge:300,
    }))

    mux.Use(middleware.Heartbeat("/ping"))
    mux.Post("/",app.Broker)

    return mux
}

This is working and the routes() function called when request received, but how does this routes() know to be triggered when it is attached to an empty struct?

app := Config{}

From where does the app know about routes()?

What is the func (app *Config) in the function?


Solution

  • Routes have been attached to the HTTP server as shown below.

    srv := &http.Server{
       Addr: ":8081", // port
       Handler: app.routes() // a handler to invoke
     }
    
    

    routes is a method of Config struct. We can still call the routes methods as in your code even when Config is empty.

     cfg := Config{}
     r := cfg.routes()
    
    

    Config struct is acting as a method receiver here.