相关疑难解决方法(0)

在Go中处理JSON Post请求

所以我有以下,看起来非常h​​acky,我一直在想自己Go有比这更好的设计库,但是我找不到Go处理JSON数据的POST请求的例子.它们都是POST形式.

这是一个示例请求: curl -X POST -d "{\"test\": \"that\"}" http://localhost:8082/test

这是代码,嵌入了日志:

package main

import (
    "encoding/json"
    "log"
    "net/http"
)

type test_struct struct {
    Test string
}

func test(rw http.ResponseWriter, req *http.Request) {
    req.ParseForm()
    log.Println(req.Form)
    //LOG: map[{"test": "that"}:[]]
    var t test_struct
    for key, _ := range req.Form {
        log.Println(key)
        //LOG: {"test": "that"}
        err := json.Unmarshal([]byte(key), &t)
        if err != nil {
            log.Println(err.Error())
        }
    }
    log.Println(t.Test)
    //LOG: that
}

func main() {
    http.HandleFunc("/test", test)
    log.Fatal(http.ListenAndServe(":8082", nil))
}
Run Code Online (Sandbox Code Playgroud)

必须有更好的方法,对吗?我很难找到最好的做法.

(Go也被称为搜索引擎的Golang,并在此处提到,以便其他人可以找到它.)

json go

230
推荐指数
6
解决办法
23万
查看次数

标签 统计

go ×1

json ×1