当我发送'GET'请求时,在Golang中返回'404 page not found'

exdqitrt  于 2023-04-27  发布在  Go
关注(0)|答案(1)|浏览(139)

我是Golang的新手。我尝试用Golang编写一个API服务器,没有任何HTTP框架(echo,gin等)。我写了'post'端点,但我的'get'端点没有响应。我尝试编写另一个名为'ping'的get端点,它工作正常。我的curl

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)
kmpatx3s

kmpatx3s1#

  • 注册处理程序时,将模式参数/users/:id更改为/users/
mux.HandleFunc("/users/", func(writer http.ResponseWriter, request *http.Request) {
     id := strings.TrimPrefix(request.URL.Path, "/users/")

     ...
})

注意:有很多第三方库可以帮助您编写可读性更强、效率更高的HTTP服务器。

示例

相关问题