0

I want to take limit and offset values from my frontend. For that, I have written the following routing path

func (s *Server) stockRoutes() {
    s.r.Route("/stock", func(r chi.Router) {
        r.Get("/{limit}{offset}", s.ListStocks(s.ctx))

        r.Route("/{id}", func(r chi.Router) {
            r.Get("/", s.GetStock(s.ctx))
            r.Put("/", s.UpdateStockDetails(s.ctx))
        })
    })
}

I am handling the request in the following fashion. I am parsing the values of limit and offset

func (s *Server) ListStocks(ctx context.Context) http.HandlerFunc {
    return func(rw http.ResponseWriter, r *http.Request) {
        param, _ := strconv.Atoi(chi.URLParam(r, "limit"))
        param2, _ := strconv.Atoi(chi.URLParam(r, "offset"))
        limit := int32(param)
        offset := int32(param2)
        arg := db.ListStocksParams{
            Limit:  limit,
            Offset: offset,
        }
        stocks, err := s.store.ListStocks(ctx, arg)
        if err != nil {
            http.Error(rw, "error returning list of stocks", http.StatusInternalServerError)
            return
        }
        log.Printf("%+v", stocks)
        json.NewEncoder(rw).Encode(stocks)
    }
}

Using postman, I am sending a request in the following way http://localhost:8000/stock?limit=5&offset=0. Can anyone help me understand what I am doing wrong?

neel229
  • 73
  • 1
  • 5
  • you're using query params, it isn't necessary to define query parameter in route definitions. Also use `r.URL.Query().Get("limit")` to get limit query param, `/{limit}{offset}` seems like an invalid/another route – Jeffy Mathew Mar 11 '21 at 12:44
  • thanks for making it clear – neel229 Mar 11 '21 at 13:33

0 Answers0