#Understanding http server implementation

12 messages · Page 1 of 1 (latest)

thorn lichen
#

How is this more efficient

type PlayerServer struct {
    store PlayerStore
    http.Handler
}

func NewPlayerServer(store PlayerStore) *PlayerServer {
    p := new(PlayerServer)

    p.store = store

    router := http.NewServeMux()
    router.Handle("/league", http.HandlerFunc(p.leagueHandler))
    router.Handle("/players/", http.HandlerFunc(p.playersHandler))

    p.Handler = router

    return p
}```
than:
```go
//server.go
func (p *PlayerServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {

    router := http.NewServeMux()
    router.Handle("/league", http.HandlerFunc(p.leagueHandler))
    router.Handle("/players/", http.HandlerFunc(p.playersHandler))

    router.ServeHTTP(w, r)
}
ancient marsh
#

instead this is cached

#

Using a switch (and or ifs and HasPrefix) would be the most efficient solution here

thorn lichen
tardy tree
#

I can't imagine the performance is meaningfully different

ancient marsh
ancient marsh
#

Also IMO, the first solution is more readable,
it uses less memory and is faster, why would you not use it ?

tardy tree
#

yes, those are good reasons

#

but performance doesn't really make a difference here. it's a bonus

ancient marsh
#

it's probably like ~1µs per request (GC accounted)