github.com/tuingking/flamingo@v0.0.0-20220403134817-2796ae0e84ca/handler/rest/product.go (about) 1 package rest 2 3 import ( 4 "fmt" 5 "net/http" 6 "strconv" 7 8 "github.com/go-chi/chi" 9 "github.com/go-chi/chi/middleware" 10 "github.com/pkg/errors" 11 "github.com/tuingking/flamingo/infra/contextkey" 12 "github.com/tuingking/flamingo/internal/auth" 13 "github.com/tuingking/flamingo/internal/product" 14 ) 15 16 // GetAllProducts 17 // @Summary get all products 18 // @Description get all products 19 // @Tags Product 20 // @Accept json 21 // @Produce json 22 // @Param paramName query string true "my param" 23 // @Success 200 {object} Response{data=[]product.Product} "Success Response" 24 // @Failure 400 "Bad Request" 25 // @Failure 500 "InternalServerError" 26 // @Router /products [get] 27 func (h *RestHandler) GetAllProducts(w http.ResponseWriter, r *http.Request) { 28 var resp Response 29 defer resp.Render(w, r) 30 31 //*** How to get chi requestID 32 requestID, ok := r.Context().Value(middleware.RequestIDKey).(string) 33 if !ok { 34 resp.SetError(errors.New("unable to get request id"), http.StatusInternalServerError) 35 return 36 } 37 h.logger.Info("requestID: ", requestID) 38 39 //** Get Session 40 fmt.Printf("[DEBUG] r.Context().Value(contextkey.Identity): %+v\n", r.Context().Value(contextkey.Identity)) 41 identity, ok := r.Context().Value(contextkey.Identity).(auth.JwtClaims) 42 if !ok { 43 h.logger.Warn("unable to get identity") 44 } 45 fmt.Printf("[DEBUG] identity: %+v\n", identity) 46 47 products, err := h.product.GetAllProducts(r.Context()) 48 if err != nil { 49 resp.SetError(errors.Wrap(err, "get all products"), http.StatusInternalServerError) 50 return 51 } 52 var respData []product.Product = products 53 54 resp.Data = respData 55 } 56 57 // Seed Product 58 // @Summary auto generate random product and populate it to database 59 // @Description auto generate random product and populate it to database 60 // @Tags Product 61 // @Accept json 62 // @Produce json 63 // @Param n path integer true "number product are going to be generated" 64 // @Success 200 {object} Response{} "Success Response" 65 // @Failure 400 "Bad Request" 66 // @Failure 500 "InternalServerError" 67 // @Router /products/seed/{n} [post] 68 func (h *RestHandler) SeedProduct(w http.ResponseWriter, r *http.Request) { 69 var resp Response 70 defer resp.Render(w, r) 71 72 n, err := strconv.Atoi(chi.URLParam(r, "n")) 73 if err != nil { 74 resp.SetError(errors.Wrap(err, "n should be a number"), http.StatusInternalServerError) 75 return 76 } 77 78 err = h.product.Seed(r.Context(), n) 79 if err != nil { 80 resp.SetError(errors.Wrap(err, "[Seed] error seeding product data"), http.StatusInternalServerError) 81 return 82 } 83 84 resp.Data = nil 85 }