dongwei4444 2014-01-09 07:27
浏览 36

将POST请求中的JSON发送到用web.go框架编写的Web API

Im using web.go (http://webgo.io/) for writing a simple web app that accepts json in a POST request and after parsing it returns the result. Im having trouble reading the json from ctx.Params object. Below is the code i have so far

package main

import  (
    "github.com/hoisie/web";
     "encoding/json"
)

func parse(ctx *web.Context, val string) string { 

    for k,v := range ctx.Params {
        println(k, v)       
    }

   //Testing json parsing
   mapB := map[string]int{"apple": 5, "lettuce": 7}
   mapD, _ := json.Marshal(mapB)
   return string(mapD)

}   

func main() {
    web.Post("/(.*)", parse)
    web.Run("0.0.0.0:9999")
}

Though the post request gets registered i dont see anything printed on the command line for the json i posted. How can i fix this ?

Thank You

  • 写回答

1条回答 默认 最新

  • duanbai5348 2014-01-09 15:57
    关注

    The reason you're not getting any JSON data from the body of the POST request is because hoisie/web reads form data into .Params, as seen here:

    req.ParseForm()
    if len(req.Form) > 0 {
        for k, v := range req.Form {
            ctx.Params[k] = v[0]
        }
    }
    

    In order to fix this, you'll need to add something that can parse the raw body of the response. You should just be able to use ctx.Body to access the raw body, since it implements *http.Request and doesn't redefine Body in the Context struct.

    For example, this should work:

    json := make(map[string]interface{})
    body, err := ioutil.ReadAll(ctx.Body)
    if err != nil {
      // Handle Body read error
      return
    }
    err = json.Unmarshal(body, &json)
    if err != nil {
      // Handle JSON parsing error
      return
    }
    // Use `json`
    
    评论

报告相同问题?