我是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)
1条答案
按热度按时间kmpatx3s1#
/users/:id
更改为/users/
。注意:有很多第三方库可以帮助您编写可读性更强、效率更高的HTTP服务器。
示例