登录
首页 >  Golang >  Go问答

如何在 GoLang 中使用 http POST 方法来执行记录更新操作?

来源:stackoverflow

时间:2024-02-19 20:12:26 450浏览 收藏

学习知识要善于思考,思考,再思考!今天golang学习网小编就给大家带来《如何在 GoLang 中使用 http POST 方法来执行记录更新操作?》,以下内容主要包含等知识点,如果你正在学习或准备学习Golang,就都不要错过本文啦~让我们一起来看看吧,能帮助到你就更好了!

问题内容

问题描述:

我正在学习 golang 来为一个小项目实现 rest api。 我正在遵循这个小例子来了解如何连接事物。 但是,示例示例中似乎存在一些错误,导致我在到达端点后无法在邮递员中获得预期响应。 我通过添加缺少的函数(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"

}

但是在到达我定义的返回所有事件的“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 handler 函数

err = json.unmarshal(reqbody, &newevent)
if err != nil {
    fmt.fprintf(w, "json format invalid")
    return
}

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

195657188​​139

以上就是《如何在 GoLang 中使用 http POST 方法来执行记录更新操作?》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>