当我发送一个’GET’请求时,在Golang中返回’404页面未找到’。

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

When I send 'GET' request, returning '404 page not found' in Golang

问题

我是你的中文翻译助手,以下是你要翻译的内容:

我是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)
英文:

I'm new on Golang. I try to write an API server with Golang without any HTTP framework(echo, gin, etc.). I wrote 'post' endpoint but my 'get' endpoint not respond. I tried to write another get endpoint named 'ping' and it was working. My curl

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

My handler

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

My main method

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)

答案1

得分: 3

在注册处理程序时,将patterns参数/users/:id更改为/users/

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

     ...
})

注意:有许多第三方库可用于帮助您编写更易读和高效的HTTP服务器。

示例

英文:
  • When registering the handler, change the patterns argument /users/:id to /users/.
mux.HandleFunc("/users/", func(writer http.ResponseWriter, request *http.Request) {
     id := strings.TrimPrefix(request.URL.Path, "/users/")

     ...
})

> Note: There are numerous third-party libraries available to assist you in writing a more readable and efficient HTTP server.
>
> Examples
>
> - Gin
> - Fiber

huangapple
  • 本文由 发表于 2023年4月19日 09:03:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76050039.html
匿名

发表评论

匿名网友

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

确定