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

我们如何在GoLang中通过http post方法更新记录?,http,go,post,endpoint,restapi,Http,Go,Post,Endpoint,Restapi,问题描述: 我正在学习Golang为一个小项目实现RESTAPI。 我一直在关注这个问题,想知道如何把事情联系起来。 然而,在示例中似乎存在一些bug,在到达端点后,我无法在postman中获得预期的响应。 我已经通过添加缺失的函数(HandleFunc函数)来修复它,使其正常工作 问题描述: 但是,我仍然对CreateEvent部分有一个问题。 我们的期望是,在对给定的示例事件(json格式)使用POST方法(如下所示)后,事件列表将更新 { "id": "

问题描述:

我正在学习Golang为一个小项目实现RESTAPI。 我一直在关注这个问题,想知道如何把事情联系起来。 然而,在示例中似乎存在一些bug,在到达端点后,我无法在postman中获得预期的响应。 我已经通过添加缺失的函数(HandleFunc函数)来修复它,使其正常工作

问题描述:

但是,我仍然对CreateEvent部分有一个问题。 我们的期望是,在对给定的示例事件(json格式)使用POST方法(如下所示)后,事件列表将更新

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

}
但在到达http://localhost:8080/events“我在其中定义为返回所有事件的端点(1个在代码中定义,另一个应通过调用CreateEvent函数添加)我在响应中只得到一个事件(硬编码的仅在代码中)

这是完整的代码。 感谢您的建议/意见

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错误,则处理它并返回

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)

谢谢你的推荐?当您点击“”端点时,是否同时获得两个事件记录?我只得到代码中硬编码的事件,而不是通过点击“”端点并调用createEvent添加的事件。是的,我得到了通过端点添加的所有事件。检查您的邮递员POST请求正文是否为原始json。