简体   繁体   中英

How to parse json post request

I want to post json data to Go api, But i can't parse json in Go

javascript code:

data= {"user":{"username":"admin","password":"123"},"profile":{"firstname":"morteza","lastname":"khadem","files":["/temp/a.jpg","/temp/b.jpg"]}}

$.post('/parse-json', data, function () {
    alert('success');
});

in php get data very simple ($_REQUEST['user']['firstname']) but in Go different

GO is different from PHP and JS. Instead of being easy to use it is focused on being explicit and reliable.

To parse JSON body in request we should have strong type struct definition to describe structure that receives payload. That is how we can control fields that should be supported. It is important as every filed has its own type and parsing fails if string from request does not match that type.

type RequestBody struct {
    User   User  `json:"user"`
    Profile Profile `json:"profile"`
}

type User struct {
    UserName   string  `json:"username"`
    Password string `json:"password"`
}

type Profile struct {
    FirstName   string  `json:"firstname"`
    LastName string `json:"lastname"`
    Files []string `json:"files"`
}


func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    decoder := json.NewDecoder(r.Body)
    var req RequestBody
    err := decoder.Decode(&req)
    if err != nil {
        // log error and return 400 to caller
        return
    }

    // Use req
}

Now i use this code:

type Merchant struct{}

func (*Merchant) Register(context context.Context){
    type registerRequestData struct{
        Merchant models.MrtMerchant `json:"merchant"`
        User models2.UsrUser `json:"user"`
        Profile models2.UsrUserProfile `json:"profile"`
        Branch models.MrtMerchantBranch `json:"branch"`
    }
    var request registerRequestData
    if err:=context.ReadJSON(&request);err!=nil{
        panic(err)
    }

    fmt.Printf("%+v\n",request)
}

If use iris framework,you can use ReadJSON function like this:

func serve(context context.Context){
    var request map[string]interface{}
    context.ReadJSON(request)
    username:=request["user"].(map[string]string)["username"]
    fmt.Println(username)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM