搜尋
首頁後端開發Golang透過 http 請求追加到現有列表

通过 http 请求追加到现有列表

php小編小新透過 http 請求追加到現有清單是一種常見的資料操作方式。透過傳送 http 請求,我們可以將新的資料追加到現有的清單中,實現資料的動態更新和增加。這種方法在網頁開發中十分常用,可以實現使用者提交資料後的即時顯示和更新。透過 http 請求追加到現有清單的操作簡單快捷,可以提高網頁的互動性和使用者體驗。無論是在前端頁面或後端邏輯中,都可以透過這種方式實現資料的追加,實現更豐富實用的功能。

問題內容

我正在使用 echo 製作一個簡單的 rest api。我有一個變量,它是以下地圖,基於我製作的這個結構:

type checklist struct {
        id         int      `json:"id"`
        title      string   `json:"title"`
        lines      []string `json:"lines"`
        authorname string   `json:"authorname"`
        authorid   int      `json:"authorid"`
        tags       []tag    `json:"tags"`
    }

    var (
        checklists    = map[int]*checklist{}
        checklistseq  = 1
        checklistlock = sync.mutex{}
    )

建立新清單並將其附加到 checklists 變數後,如何發送在新清單的「行」欄位中附加新行的請求?

我想到的解決方案是這樣的:

func createchecklist(c echo.context) error {
        checklistlock.lock()
        defer checklistlock.unlock()
        newchecklist := &checklist{
            id:    checklistseq,
            lines: make([]string, 0),
            tags:  make([]tag, 0),
        }
        if err := c.bind(newchecklist); err != nil {
            return err
        }
        checklists[newchecklist.id] = newchecklist
        checklistseq++
        return c.json(http.statusok, newchecklist)
    }
    func addline(c echo.context) error {
        checklistlock.lock()
        defer checklistlock.unlock()
        id, _ := strconv.atoi(c.param("id"))
        checklist := *checklists[id]
        line := []string{""}
        if err := c.bind(line); err != nil {
            return err
        }
        checklist.lines = line
        return c.json(http.statuscreated, checklists)
    }

但是,當我測試此處理程序時,它給出了以下結果:

// 1: Creating a new checklist

    $ curl -X POST -H 'Content-Type: application/json' -d '{"title": "test"}' localhost:1234/checklist

    >> {"id":1,"title":"test","lines":[],"authorName":"","authorID":0,"tags":[]}

    // 2: Check to see the checklist has been created.
 
    $ curl -X GET localhost:1234/checklist

    >> {"1":{"id":1,"title":"test","lines":[],"authorName":"","authorID":0,"tags":[]}}
    // 3: Attempting to create a new line
    $ curl -X POST -H 'Content-Type: application/json' -d '{"lines": "test123"}' localhost:1234/checklist/1

    >> curl: (52) Empty reply from server

    // 4: Confirming it hasn't been created.

    $ curl -X GET localhost:1234/checklist

    >> {"1":{"id":1,"title":"test","lines":[],"authorName":"","authorID":0,"tags":[]}}

因此該函數實際上不起作用,因為將 post ping 到適當的路由時既沒有傳回預期的回應,也沒有將該行實際新增至欄位。

解決方法

func addline(c echo.context) error {
    checklistlock.lock()
    defer checklistlock.unlock()

    id, err := strconv.atoi(c.param("id"))
    if err != nil {
        return err
    }

    // do not deref *checklist
    cl, ok := checklists[id]
    if !ok {
        return echo.errnotfound
    }

    // use same structure as the expected json
    var input struct { lines []string `json:"lines"` }

    // always pass a pointer to c.bind
    if err := c.bind(&input); err != nil {
        return err
    }

    // do not overwrite previously written lines, use append
    cl.lines = append(cl.lines, input.lines...)

    return c.json(http.statusok, cl)
}

現在嘗試:

$ curl -X POST -H 'Content-Type: application/json' -d '{"lines": ["test123"]}' localhost:1234/checklist/1

(注意 "test123" 括在括號中)

#

以上是透過 http 請求追加到現有列表的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:stackoverflow。如有侵權,請聯絡admin@php.cn刪除
Golang vs. Python:並發和多線程Golang vs. Python:並發和多線程Apr 17, 2025 am 12:20 AM

Golang更適合高並發任務,而Python在靈活性上更有優勢。 1.Golang通過goroutine和channel高效處理並發。 2.Python依賴threading和asyncio,受GIL影響,但提供多種並發方式。選擇應基於具體需求。

Golang和C:性能的權衡Golang和C:性能的權衡Apr 17, 2025 am 12:18 AM

Golang和C 在性能上的差異主要體現在內存管理、編譯優化和運行時效率等方面。 1)Golang的垃圾回收機制方便但可能影響性能,2)C 的手動內存管理和編譯器優化在遞歸計算中表現更為高效。

Golang vs. Python:申請和用例Golang vs. Python:申請和用例Apr 17, 2025 am 12:17 AM

selectgolangforhighpperformanceandcorrency,ifealforBackendServicesSandNetwork程序; selectpypypythonforrapiddevelopment,dataScience和machinelearningDuetoitsverserverserverserversator versator anderticality andextility andextentensivelibraries。

Golang vs. Python:主要差異和相似之處Golang vs. Python:主要差異和相似之處Apr 17, 2025 am 12:15 AM

Golang和Python各有优势:Golang适合高性能和并发编程,Python适用于数据科学和Web开发。Golang以其并发模型和高效性能著称,Python则以简洁语法和丰富库生态系统著称。

Golang vs. Python:易於使用和學習曲線Golang vs. Python:易於使用和學習曲線Apr 17, 2025 am 12:12 AM

Golang和Python分別在哪些方面更易用和學習曲線更平緩? Golang更適合高並發和高性能需求,學習曲線對有C語言背景的開發者較平緩。 Python更適合數據科學和快速原型設計,學習曲線對初學者非常平緩。

表演競賽:Golang vs.C表演競賽:Golang vs.CApr 16, 2025 am 12:07 AM

Golang和C 在性能競賽中的表現各有優勢:1)Golang適合高並發和快速開發,2)C 提供更高性能和細粒度控制。選擇應基於項目需求和團隊技術棧。

Golang vs.C:代碼示例和績效分析Golang vs.C:代碼示例和績效分析Apr 15, 2025 am 12:03 AM

Golang適合快速開發和並發編程,而C 更適合需要極致性能和底層控制的項目。 1)Golang的並發模型通過goroutine和channel簡化並發編程。 2)C 的模板編程提供泛型代碼和性能優化。 3)Golang的垃圾回收方便但可能影響性能,C 的內存管理複雜但控制精細。

Golang的影響:速度,效率和簡單性Golang的影響:速度,效率和簡單性Apr 14, 2025 am 12:11 AM

goimpactsdevelopmentpositationality throughspeed,效率和模擬性。 1)速度:gocompilesquicklyandrunseff,IdealforlargeProjects.2)效率:效率:ITScomprehenSevestAndardArdardArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdEcceSteral Depentencies,增強的Depleflovelmentimency.3)簡單性。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
1 個月前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
1 個月前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
1 個月前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.聊天命令以及如何使用它們
1 個月前By尊渡假赌尊渡假赌尊渡假赌

熱工具

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具