Go语言 返回空字符串

qxgroojn  于 12个月前  发布在  Go
关注(0)|答案(1)|浏览(105)

我是Go的新手,所以我尝试使用Chi构建一个简单的CRUD API。在GetById处理程序中,我使用chi.URLParam()方法从URL中检索数据,但此方法返回空字符串“"。检查代码:

func GetBookByIDHandler(w http.ResponseWriter, r *http.Request) {
    db, err := repository.OpenConnection()
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        log.Printf("Error while opening connection: %v", err)
        return
    }
    defer db.Close()

    repo := repository.NewBookSQLRepository(db)
    useCase := usecases.NewFindBookByIDUseCase(repo)

    idParam := chi.URLParam(r, "id")
    //idParams = ""

    var input usecases.FindBookByIDInput
    input.ID = idParam

    output, err := useCase.FindBookByID(input)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        log.Printf("Error while getting book by id: %v", err)
        return
    }

    w.WriteHeader(http.StatusOK)
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(output)
}

字符串
我的路由器构建如下:

r := chi.NewRouter()
    r.Get("/books", handlers.GetAllBooksHandler)
    r.Get("/books/{id}", handlers.GetBookByIDHandler)
    r.Post("/books", handlers.CreateBookHandler)


我在下面的URL中对HTTP请求使用Increase:http://localhost:8080/books/10
我已经尝试将查询参数作为"?id=10"传递请求,但它不起作用。

8e2ybdfx

8e2ybdfx1#

我有完全相同的问题,没有答案给我,但我有一个解决办法,以传统的方式提取id,下面是你的代码的工作版本:

func GetBookByIDHandler(w http.ResponseWriter, r *http.Request) {
    db, err := repository.OpenConnection()
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        log.Printf("Error while opening connection: %v", err)
        return
    }
    defer db.Close()

    repo := repository.NewBookSQLRepository(db)
    useCase := usecases.NewFindBookByIDUseCase(repo)

    // Split the URL path and extract the book id
    parts := strings.Split(r.URL.Path, "/")
    if len(parts) < 2 {
        logger.Error(fmt.Sprintf("GetBookByID, Book ID not found"))
        WriteJSON(w, http.StatusBadRequest, models.Response[any]{
            Success: false,
            Message: fmt.Sprintf("Book ID not found"),
        })
        return
    }

    idParams := parts[2]

    // Assuming your book id is defined as integer in your database
    id, err := strconv.Atoi(idParams)
    if err != nil {
        logger.Error(fmt.Sprintf("GetBookByID, invalid ID: %s", id))
        WriteJSON(w, http.StatusBadRequest, models.Response[any]{
            Success: false,
            Message: fmt.Sprintf("invalid ID: %s", id),
        })
        return
    }

    var input usecases.FindBookByIDInput
    input.ID = id

    output, err := useCase.FindBookByID(input)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        log.Printf("Error while getting book by id: %v", err)
        return
    }

    w.WriteHeader(http.StatusOK)
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(output)
   }
}

字符串

相关问题