我们如何在 Go 语言中通过 http post 方法更新记录?

How can we update a record by a http post method in GoLang?

问题描述:

我正在学习 Golang 来为一个小项目实现 REST API。 我正在关注 this small example 以了解如何连接事物。 但是,示例示例中似乎存在一些错误,在到达端点后我无法在邮递员中获得预期的响应。 我已通过添加缺少的函数(HandleFunc 函数)使其正常工作来修复它。

问题描述:

但是,CreateEvent 部分仍然存在问题。 预期是在使用 POST 方法和给定的示例事件(json 格式)后,如下所示,事件列表被更新。

{
    "id": "23",
    "title": "This is simple Go lang title for test!",
    "Description":"In this course you will learn REST api implementation in Go lang"

}

但是在到达我定义为 return 所有事件的“http://localhost:8080/events”端点之后(1 个在代码中定义,另一个应该通过调用 CreateEvent 函数添加)我只得到其中一个事件(仅硬编码一个内部代码)作为响应。

这是完整的代码。 我感谢任何 suggestions/comments.

package main

import (
        "fmt"
        "log"
        "net/http"
        "io/ioutil"
    
    "encoding/json"
        "github.com/gorilla/mux"
)

func homeLink(w http.ResponseWriter, r *http.Request) {
        fmt.Println("test started!")
        fmt.Fprintf(w, "Welcome home!")
}

func main() {
        router := mux.NewRouter().StrictSlash(true)
        router.HandleFunc("/", homeLink)
/*i have added the next 3 lines, missing in the sample code*/
        router.HandleFunc("/event", createEvent)
        router.HandleFunc("/events/{id}", getOneEvent)
        router.HandleFunc("/events", getAllEvents)
        log.Fatal(http.ListenAndServe(":8080", router))
}

type event struct {
    ID          string `json:"ID"`
    Title       string `json:"Title"`
    Description string `json:"Description"`
}

type allEvents []event

var events = allEvents{
    {
        ID:          "1",
        Title:       "Introduction to Golang",
        Description: "Come join us for a chance to learn how golang works and get to eventually try it out",
    },
}

func createEvent(w http.ResponseWriter, r *http.Request) {
    var newEvent event
    reqBody, err := ioutil.ReadAll(r.Body)
    if err != nil {
        fmt.Fprintf(w, "Kindly enter data with the event title and description only in order to update")
    }

        fmt.Println("Create Event is called!")
    json.Unmarshal(reqBody, &newEvent)
    events = append(events, newEvent)
    w.WriteHeader(http.StatusCreated)

    json.NewEncoder(w).Encode(newEvent)
}

func getOneEvent(w http.ResponseWriter, r *http.Request) {
    eventID := mux.Vars(r)["id"]

        fmt.Println("get one event is called!")
        fmt.Println(eventID)
    for _, singleEvent := range events {
        if singleEvent.ID == eventID {
            json.NewEncoder(w).Encode(singleEvent)
        }
    }
}


func getAllEvents(w http.ResponseWriter, r *http.Request) {

        fmt.Println("Get all events is called!")
    json.NewEncoder(w).Encode(events)
}

您的代码运行良好。我已经对其进行了测试(只是在我的本地机器上复制了上面的代码和 运行 并使用 Postman 进行了测试)。

顺便说一句,我在下面添加了一些建议以获得更好的代码。

如果不是nil error,则处理,return.

reqBody, err := ioutil.ReadAll(r.Body)
if err != nil {
    fmt.Fprintf(w, "Kindly enter data with the event title and description only in order to update")
    return //add this return, otherwise continue the function with the error
}

将此 json 错误处理用于 createEvent 处理程序函数

err = json.Unmarshal(reqBody, &newEvent)
if err != nil {
    fmt.Fprintf(w, "json format invalid")
    return
}

将 http 方法添加到您的端点。

router.HandleFunc("/", homeLink).Methods(http.MethodGet)
/*i have added the next 3 lines, missing in the sample code*/
router.HandleFunc("/event", createEvent).Methods(http.MethodPost)
router.HandleFunc("/events/{id}", getOneEvent).Methods(http.MethodGet)
router.HandleFunc("/events", getAllEvents).Methods(http.MethodGet)