当我发送“GET”请求时,在 Golang 中返回“找不到 404 页面”

问题描述 投票:0回答:0

我是 Golang 的新手。我尝试在没有任何 HTTP 框架(echo、gin 等)的情况下使用 Golang 编写 API 服务器。我写了“发布”端点,但我的“获取”端点没有响应。我尝试编写另一个名为“ping”的获取端点,它正在运行。我的卷曲

curl --location 'http://localhost:8080/users/45254424-5be1-487d-9131-bad3b2f7791c'

我的经纪人

func (u UserHandler) GetById(writer http.ResponseWriter, request *http.Request) {
    id := strings.TrimPrefix(request.URL.Path, "/users/")
    user := u.userService.GetById(uuid.Must(uuid.Parse(id)))
    writer.Header().Set("Content-Type", "application/json")
    json.NewEncoder(writer).Encode(user)
}

我的主要方法

postgresConnection := db.NewDb()
userRepository := repository.NewUserRepository(postgresConnection)
userService := service.NewUserService(userRepository)
userHandler := handlers.NewUserHandler(userService)

mux := http.NewServeMux()
mux.HandleFunc("/users", func(writer http.ResponseWriter, request *http.Request) {
    if request.Method == "POST" {
        userHandler.Create(writer, request)
    } else {
        http.Error(writer, "Invalid request method", http.StatusMethodNotAllowed)
    }
})
mux.HandleFunc("/users/:id", func(writer http.ResponseWriter, request *http.Request) {
    if request.Method == "GET" {
        userHandler.GetById(writer, request)
    } else {
        http.Error(writer, "Invalid request method", http.StatusMethodNotAllowed)
    }
})
mux.HandleFunc("/ping", PingHandler)

err := http.ListenAndServe(":8080", mux)
log.Fatal(err)
rest go http
© www.soinside.com 2019 - 2024. All rights reserved.