Vish K
Vish K

Reputation: 135

Golang rest api concurrency

I am writing the rest api in golang with the following structure

Handler classes:

type Controller struct {
    db daos.IUserDB
}

func NewController(db daos.IUserDB) *Controller{
    return &Controller{db:db}
}


func (c *Controller) Test(w http.ResponseWriter, r *http.Request)  {

    fmt.Fprintf(w, "Welcome to the HomePage!")
}

func (c *Controller) RegisterRoutes(r *mux.Router){
    r.HandleFunc("/test", c.Test).Methods("GET")
}

DAO classes

type IUserDB interface {
    Get
    GetByID ... 
}


type userDAO struct {
    db *sql.DB
}


func NewDB(dataSourceName string) (*userDAO, error) {
    db, err := sql.Open("mysql", dataSourceName)
    if err != nil {
        return nil, err
    }
    if err = db.Ping(); err != nil {
        return nil, err
    }
    return &userDAO{db}, nil
}

func (dao *userDAO) Get(){
}

func (dao *userDAO) GetByID(){
}

main class

func main() {

    db, err := daos.NewDB(connectionStr)
    if err != nil {
        log.Panic(errr)
    }
    handler := handlers.NewController(db)

    router := mux.NewRouter()
    handler.RegisterRoutes(router)

    log.Printf("serving on port 8080")
    http.ListenAndServe(":3000", router)
}

Question:

We are creating only one instance of Handler and Repository objects. (will make another service interface also)

How golang achieve concurrency with this setup for simultaneous many request ?

For every request the same object of handler or db will be used ?

Help to clarify this design ?

Upvotes: 2

Views: 6954

Answers (2)

Thundercat
Thundercat

Reputation: 121139

The net/http server automatically starts a new goroutine for each client connection and executes request handlers in those goroutines. The application does not need to do anything special to serve requests concurrently.

The single mux, controller and db values are used for all requests, and possibly concurrently.

Use a mutex to protect these values if they are not thread-safe. The mux (assuming you are using gorilla/mux) and the controller (as currently written) are both thread-safe. No mutex is needed for those values. I don't know what the daos package is, so I cannot comment on the necessity of using a mutex to protect the db value.

Upvotes: 5

GilesW
GilesW

Reputation: 515

The concurrency happens inside the router - it will start a separate goroutine for each messaged received that uses the handler. Repository instances will be shared so don't put any code in there that isn't concurrency safe.

Upvotes: 3

Related Questions