ObjectIdFromHex在相同字符串上出现无效字节错误

huangapple go评论119阅读模式
英文:

ObjectIdFromHex invalid byte error on identical strings

问题

我正在尝试在我的 Golang REST API 中实现一个 FindOne 方法。问题出在当我需要通过 ID 进行搜索时。我必须将 ID 转换为数据库可读的格式,所以我使用了 primitive.ObjectIDFromHex(id) 方法。
问题是,当我使用来自 URL GET 参数的 id 调用该方法时,它会抛出一个错误:

  1. 2021/06/19 06:56:15 encoding/hex: invalid byte: U+000A

只有当我使用硬编码的 ID 调用它时,不会出现这个编码错误。请参考下面的代码。

  1. func Admin(id string) (bson.M, error) {
  2. coll, err := db.ConnectToCollection("admin")
  3. if err != nil {
  4. log.Fatal(err)
  5. }
  6. var admin bson.M
  7. HardCoded := "60cb275c074ab46a1aeda45e"
  8. fmt.Println(HardCoded) // 为了确保:这两个字符串看起来是相同的
  9. fmt.Println(id)
  10. objetId, err := primitive.ObjectIDFromHex(id) // 抛出编码错误
  11. // objetId, err := primitive.ObjectIDFromHex(HardCoded) // 不会抛出编码错误
  12. if err != nil {
  13. log.Fatal(err)
  14. }
  15. var ctx = context.TODO()
  16. if err := coll.FindOne(ctx, bson.M{"_id": objetId}).Decode(&admin); err != nil {
  17. log.Fatal(err)
  18. }
  19. return admin, nil
  20. }

当然,你可能想知道参数 id 是从哪里来的。
这是代码:

  1. func GetAdmin(w http.ResponseWriter, r *http.Request) {
  2. w.Header().Set("Content-Type", "application/json")
  3. params := mux.Vars(r)
  4. admin, err := Admin(params["id"]) // 调用上面的 Admin 函数
  5. if err != nil {
  6. fmt.Println(err)
  7. http.Error(w, err.Error(), http.StatusUnauthorized)
  8. } else {
  9. JSON, err := json.Marshal(admin)
  10. if err != nil {
  11. http.Error(w, err.Error(), http.StatusInternalServerError)
  12. }
  13. w.Write(JSON)
  14. }
  15. }
英文:

I'm trying to implement a FindOne method in my Golang REST API. The trouble comes where i have to search by ID. I have to convert the ID into something readable by the database, so i use primitive.ObjectIDFromHex(id)
The problem is that this method throws an error :

  1. 2021/06/19 06:56:15 encoding/hex: invalid byte: U+000A

ONLY when i call it with the id that comes from my URL GET params.
I did two versions : one with hard-coded ID, and one with GET ID. See code below.

  1. func Admin(id string) (bson.M, error) {
  2. coll, err := db.ConnectToCollection("admin")
  3. if err != nil {
  4. log.Fatal(err)
  5. }
  6. var admin bson.M
  7. HardCoded := "60cb275c074ab46a1aeda45e"
  8. fmt.Println(HardCoded) // Just to be sure : the two strings seem identical
  9. fmt.Println(id)
  10. objetId, err := primitive.ObjectIDFromHex(id) // throws encoding error
  11. // objetId, err := primitive.ObjectIDFromHex(HardCoded) // Doesnt throw encoding err
  12. if err != nil {
  13. log.Fatal(err)
  14. }
  15. var ctx = context.TODO()
  16. if err := coll.FindOne(ctx, bson.M{"_id": objetId}).Decode(&admin); err != nil {
  17. log.Fatal(err)
  18. }
  19. return admin, nil
  20. }

Of course, you'll want to know where the param id comes from.
Here you go :

  1. func GetAdmin(w http.ResponseWriter, r *http.Request) {
  2. w.Header().Set("Content-Type", "application/json")
  3. params := mux.Vars(r)
  4. admin, err := Admin(params["id"]) // Calling the Admin function above
  5. if err != nil {
  6. fmt.Println(err)
  7. http.Error(w, err.Error(), http.StatusUnauthorized)
  8. } else {
  9. JSON, err := json.Marshal(admin)
  10. if err != nil {
  11. http.Error(w, err.Error(), http.StatusInternalServerError)
  12. }
  13. w.Write(JSON)
  14. }
  15. }

答案1

得分: 3

修剪 id 结尾的换行符:

id = strings.TrimSpace(id)

在调试此类问题时,使用 %q 格式化动词。换行符在此输出中清晰可见:

fmt.Printf("%q\n", HardCoded) // 输出 "60cb275c074ab46a1aeda45e"
fmt.Printf("%q\n", id) // 输出 "60cb275c074ab46a1aeda45e\n"

英文:

Trim the line feed from the end of id:

  1. id = strings.TrimSpace(id)

Use the %q format verb when debugging issues like this. The line feed is clearly visible in this output:

  1. fmt.Printf("%q\n", HardCoded) // prints "60cb275c074ab46a1aeda45e"
  2. fmt.Printf("%q\n", id) // prints "60cb275c074ab46a1aeda45e\n"

huangapple
  • 本文由 发表于 2021年6月19日 13:17:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/68043857.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定