Video:

Implementing the GetRocket gRPC Handler

May 22, 2021

Course Instructor: Elliot Forbes

Hey Gophers! My name is Elliot and I'm the creator of TutorialEdge and I've been working with Go systems for roughly 5 years now.

Twitter: @Elliot_f

In the last video, we looked at how we could implement the basic gRPC server with stubbed out methods for our handler functions.

In this video, we are going to be looking at how we can implement the first of our handler functions which will allow us to retrieve a rocket from the database by it’s ID.

Updating our Handler.go

Let’s dive into our handler.go file and update the GetRocket handler func:

// GetRocket - retrieves a rocket by id and returns the response.
func (h Handler) GetRocket(ctx context.Context, req *rkt.GetRocketRequest) (*rkt.GetRocketResponse, error) {
	log.Print("Get Rocket gRPC Endpoint Hit")

	rocket, err := h.RocketService.GetRocketByID(ctx, req.Id)
	if err != nil {
		log.Print("Failed to retrieve rocket by ID")
		return &rkt.GetRocketResponse{}, err
	}

	return &rkt.GetRocketResponse{
		Rocket: &rkt.Rocket{
			Id:   rocket.ID,
			Name: rocket.Name,
			Type: rocket.Type,
		},
	}, nil
}

Updating the db Package

Next, let’s finish off the implementation of the GetRocketByID function within our db package:

// GetRocketByID - retrieves a rocket from the database and returns it or an error.
func (s Store) GetRocketByID(id string) (rocket.Rocket, error) {
	var rkt rocket.Rocket
	row := s.db.QueryRow(
		`SELECT id FROM rockets WHERE id=(?)::uuid`,
		id,
	)
	err := row.Scan(&rkt)
	if err != nil {
		return rocket.Rocket{}, err
	}
	return rkt, nil
}

Conclusion

Perfect, in the next video, we are going to take a look at implementing the AddRocket gRPC handler function and it’s corresponding database function which will allow us to manually test to see if this implementation is working as expected!