mirror of
				https://github.com/3ybactuk/marketplace-go-service-project.git
				synced 2025-10-31 14:33:45 +03:00 
			
		
		
		
	
		
			
				
	
	
		
			59 lines
		
	
	
		
			1.2 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
			
		
		
	
	
			59 lines
		
	
	
		
			1.2 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
| package server
 | |
| 
 | |
| import (
 | |
| 	"encoding/json"
 | |
| 	"errors"
 | |
| 	"fmt"
 | |
| 	"net/http"
 | |
| 	"strconv"
 | |
| 
 | |
| 	"route256/cart/internal/domain/entity"
 | |
| 	"route256/cart/internal/domain/model"
 | |
| 
 | |
| 	"github.com/rs/zerolog/log"
 | |
| )
 | |
| 
 | |
| type CheckoutResponse struct {
 | |
| 	OrderID int64 `json:"order_id"`
 | |
| }
 | |
| 
 | |
| func (s *Server) CheckoutHandler(w http.ResponseWriter, r *http.Request) {
 | |
| 	strUserID := r.PathValue("user_id")
 | |
| 	userID, err := strconv.ParseInt(strUserID, 10, 64)
 | |
| 	if err != nil || userID <= 0 {
 | |
| 		if err == nil {
 | |
| 			err = fmt.Errorf("user_id must be greater than 0")
 | |
| 		}
 | |
| 
 | |
| 		makeErrorResponse(w, err, http.StatusBadRequest)
 | |
| 
 | |
| 		log.Trace().Err(err).Msgf("user_id=`%s`", strUserID)
 | |
| 
 | |
| 		return
 | |
| 	}
 | |
| 
 | |
| 	orderID, err := s.cartService.CheckoutUserCart(r.Context(), entity.UID(userID))
 | |
| 	switch {
 | |
| 	case errors.Is(err, model.ErrCartNotFound):
 | |
| 		makeErrorResponse(w, err, http.StatusNotFound)
 | |
| 
 | |
| 		return
 | |
| 	case err != nil:
 | |
| 		makeErrorResponse(w, err, http.StatusInternalServerError)
 | |
| 
 | |
| 		return
 | |
| 	}
 | |
| 
 | |
| 	resp := CheckoutResponse{
 | |
| 		OrderID: orderID,
 | |
| 	}
 | |
| 
 | |
| 	w.Header().Add("Content-Type", "application/json")
 | |
| 	w.WriteHeader(http.StatusOK)
 | |
| 	if err := json.NewEncoder(w).Encode(resp); err != nil {
 | |
| 		makeErrorResponse(w, err, http.StatusInternalServerError)
 | |
| 
 | |
| 		return
 | |
| 	}
 | |
| }
 | 
