Do each HTTP requests create a new copy of handler object?

Hi,

I am wondering if I go given setup with no pointer receivers, do each HTTP requests create a new copy of User, Service and Storage objects in memory, or do they get created once and used for consequent HTTP requests?

Thanks

package main

import (
	"database/sql"
	"net/http"
)

func main() {
	storage := Storage{
		Database: nil, // Actual DB goes here
	}

	service := Service{
		Storage: storage,
	}

	user := User{
		Service: service,
	}

	mux := http.DefaultServeMux

	mux.HandleFunc("/create", user.Post)

	// ...
}

type User struct {
	Service Service
}

func (u User) Post(w http.ResponseWriter, r *http.Request) {
	// ...
	u.Service.create( /**/ )
	// ...
}

type Service struct {
	Storage Storage
}

func (s Service) create( /**/ ) {
	// ...
	s.Storage.insert( /**/ )
	// ...
}

type Storage struct {
	Database *sql.DB
}

func (s Storage) insert( /**/ ) {
	// ...
}

Copies are created to pass to every function that is called with a value receiver instead of a pointer receiver, so copies are made for each of these calls:

func (u User) Post(w http.ResponseWriter, r *http.Request)
func (s Service) create( /**/ )
func (s Storage) insert( /**/ )

(*http.ServeMux).HandleFunc’s handler parameter has type func(http.ResponseWriter, *httpRequest), so user.Post is effectively “wrapped” into a closure so that every time the ServeMux calls handler, the User is copied into Post’s stack frame so it can execute. Then when Post calls Service.create, it too copies its embedded Service into create’s stack frame, etc…

That being said, in your example, sizeof(User{}) == sizeof(Service{}) == sizeof(Storage{}) == sizeof(*sql.DB), so you’re effectively just passing a single pointer which is extremely efficient, so you have nothing to worry about (assuming you’re asking because you’re worried about copies).

Yes that’s what I was thinking about. Thank you for the explanation. Much appreciated.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.