Golang中Get API未返回customerId的解决方法

Golang中Get API未返回customerId的解决方法 大家好,

我在数据模型中添加了customerId字段。但仍然是同样的404错误。没有返回客户ID。 有人能帮忙吗?非常感谢。

代码:

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"
    "github.com/gorilla/mux"
)

type Customer struct {
    FullName   string
    City       string
    ZipCode    string
    CustomerId int
}

func main() {
    router := http.NewServeMux()
    router.HandleFunc("/greet", myHandler)
    router.HandleFunc("/customers", customers)
    router.HandleFunc("/customers/{CustomerId}", getCustomer)
    log.Fatal(http.ListenAndServe("localhost:8080", router))
}

func myHandler(w http.ResponseWriter, c *http.Request) {
    fmt.Fprint(w, "Hello World, Welcome to the world of GOlang REST API")
}

func getCustomer(w http.ResponseWriter, c *http.Request) {
    vars := mux.Vars(c)
    fmt.Fprint(w, vars["CustomerId"])
}

func customers(w http.ResponseWriter, c *http.Request) {
    curt := []Customer{
        {FullName: "Alice", City: "Canada", ZipCode: "100090", CustomerId: 12345},
        {FullName: "Bob", City: "Japan", ZipCode: "100095", CustomerId: 90000},
        {FullName: "Marshall", City: "Australia", ZipCode: "100096", CustomerId: 12345},
    }
    w.Header().Add("Content-Type", "application/json")
    json.NewEncoder(w).Encode(curt)
}

输出:


更多关于Golang中Get API未返回customerId的解决方法的实战教程也可以访问 https://www.itying.com/category-94-b0.html

8 回复

我是新来的。我同意。

更多关于Golang中Get API未返回customerId的解决方法的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


是的,在我的代码中,我已经初始化了它。所以重新赋值会导致错误。感谢你的反馈。

哦! 嘿,Go 开发伙伴, 我也遇到了同样的问题。你解决了吗?

@Sibert 引号没有问题。问题出在路由器这一行。

这才是正确的解决方案。我通过查看互联网上的其他例子弄明白了。

router := http.NewServeMux()

这是错误的。

router := mux.NewRouter()

这才是正确的。

是的,能够解决这个问题。 这是正确的解决方案。我通过查看网上的其他例子弄明白了。 router := http.NewServeMux() – 这是错误的 router := mux.NewRouter() – 这是正确的。

router := http.NewServeMux()
router := mux.NewRouter()

shubhragrag:

有人能帮帮忙吗?

prog.go:5:1: 非法字符 U+201C ‘“’ (以及另外 43 个错误)

Go Playground - The Go Programming Language

是的,也不完全是。如果你将代码作为文本粘贴到问题中(比较文本“fmt”和代码 "fmt"),双引号会显示为错误的字符。将代码剪切并粘贴到playground中,它们会显示为非法字符 U+201C ‘“’。

请使用“代码”图标或 ```(三个反引号)来包裹你的代码,以降低他人查看你代码的门槛。

你的代码存在几个问题导致无法正确获取customerId:

  1. 路由库不匹配:你使用了http.NewServeMux()但尝试使用mux.Vars(),这是gorilla/mux库的功能
  2. 路径参数名称不一致:路由定义使用{CustomerId}但结构体字段是CustomerId(注意大小写)

解决方案:

方案1:使用gorilla/mux(推荐)

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"
    "strconv"
    "github.com/gorilla/mux"
)

type Customer struct {
    FullName   string `json:"fullName"`
    City       string `json:"city"`
    ZipCode    string `json:"zipCode"`
    CustomerId int    `json:"customerId"`
}

func main() {
    router := mux.NewRouter()
    router.HandleFunc("/greet", myHandler)
    router.HandleFunc("/customers", customers)
    router.HandleFunc("/customers/{customerId}", getCustomer)
    log.Fatal(http.ListenAndServe("localhost:8080", router))
}

func myHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "Hello World, Welcome to the world of GOlang REST API")
}

func getCustomer(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    customerId := vars["customerId"]
    
    // 将字符串转换为整数
    id, err := strconv.Atoi(customerId)
    if err != nil {
        http.Error(w, "Invalid customer ID", http.StatusBadRequest)
        return
    }
    
    // 模拟从数据库获取客户数据
    customer := Customer{
        FullName:   "Test Customer",
        City:       "Test City",
        ZipCode:    "12345",
        CustomerId: id,
    }
    
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(customer)
}

func customers(w http.ResponseWriter, r *http.Request) {
    customers := []Customer{
        {FullName: "Alice", City: "Canada", ZipCode: "100090", CustomerId: 12345},
        {FullName: "Bob", City: "Japan", ZipCode: "100095", CustomerId: 90000},
        {FullName: "Marshall", City: "Australia", ZipCode: "100096", CustomerId: 12346},
    }
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(customers)
}

方案2:使用标准库(不使用gorilla/mux)

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"
    "strconv"
    "strings"
)

type Customer struct {
    FullName   string `json:"fullName"`
    City       string `json:"city"`
    ZipCode    string `json:"zipCode"`
    CustomerId int    `json:"customerId"`
}

func main() {
    router := http.NewServeMux()
    router.HandleFunc("/greet", myHandler)
    router.HandleFunc("/customers", customers)
    router.HandleFunc("/customers/", getCustomer) // 注意这里的斜杠
    log.Fatal(http.ListenAndServe("localhost:8080", router))
}

func myHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "Hello World, Welcome to the world of GOlang REST API")
}

func getCustomer(w http.ResponseWriter, r *http.Request) {
    // 从URL路径中提取customerId
    pathParts := strings.Split(r.URL.Path, "/")
    if len(pathParts) < 3 {
        http.Error(w, "Customer ID not found", http.StatusBadRequest)
        return
    }
    
    customerId := pathParts[2]
    id, err := strconv.Atoi(customerId)
    if err != nil {
        http.Error(w, "Invalid customer ID", http.StatusBadRequest)
        return
    }
    
    customer := Customer{
        FullName:   "Test Customer",
        City:       "Test City",
        ZipCode:    "12345",
        CustomerId: id,
    }
    
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(customer)
}

func customers(w http.ResponseWriter, r *http.Request) {
    customers := []Customer{
        {FullName: "Alice", City: "Canada", ZipCode: "100090", CustomerId: 12345},
        {FullName: "Bob", City: "Japan", ZipCode: "100095", CustomerId: 90000},
        {FullName: "Marshall", City: "Australia", ZipCode: "100096", CustomerId: 12346},
    }
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(customers)
}

测试方法:

使用curl测试API:

# 获取所有客户
curl http://localhost:8080/customers

# 获取特定客户(使用方案1的gorilla/mux版本)
curl http://localhost:8080/customers/12345

主要修改:

  1. 统一使用gorilla/mux或标准库,不要混用
  2. 路径参数使用小写({customerId}而不是{CustomerId}
  3. 添加JSON标签确保正确序列化
  4. 正确处理路径参数提取和类型转换
回到顶部