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

2024年 2月 13日 51.7k 0

当我发送“get”请求时,在 golang 中返回“404 页面未找到”

php小编百草在介绍Golang中的请求处理时,强调了当发送GET请求时,可能会遇到的404页面未找到的问题。Golang作为一种高效且强大的编程语言,可以通过适当的处理来解决这个问题,确保用户能够得到正确的响应。在编写代码时,需要注意使用适当的错误处理机制,以及正确的路径和路由配置,以避免404错误的发生。这样,用户就能够享受到更好的网页浏览体验。

问题内容

我是 golang 新手。我尝试使用 golang 编写一个 api 服务器,而不使用任何 http 框架(echo、gin 等)。我写了“post”端点,但我的“get”端点没有响应。我尝试编写另一个名为“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)

登录后复制

解决方法

  • 注册处理程序时,将模式参数 /users/:id 更改为 /users/

mux.HandleFunc("/users/", func(writer http.ResponseWriter, request *http.Request) {
id := strings.TrimPrefix(request.URL.Path, "/users/")

...
})

登录后复制

注意:有许多第三方库可以帮助您编写更具可读性和更高效的 http 服务器。

示例

  • 杜松子酒
  • 光纤

以上就是当我发送“GET”请求时,在 Golang 中返回“404 页面未找到”的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论