How to POST to GO HTTP server with size of the json unknow

  Kiến thức lập trình

I have HTTP server with a POST method in GO language and Im trying to tie it to the call from another service, but the size and structure of a json is unknown, or can vary. One call can be 10 repeated db model structs, but the next one can have be a struct where it has more fields and could have a different number of stucts in a single call – say 20. How do I go about unmarshalling it and shoving it into a database?

I have a function read json that doesnt really have a read limit, but do I pack it into a structure?

func (app *application) readJSON(w http.ResponseWriter, r *http.Request, data interface{}) error{
    maxBytes := 1024*1024 // one megabyte
    r.Body = http.MaxBytesReader(w, r.Body, int64(maxBytes))

    dec := json.NewDecoder((r.Body))

    dec.DisallowUnknownFields()

    err := dec.Decode(data)
    if err != nil {
        return err
    }
    err = dec.Decode(&struct{}{})
    if err != io.EOF {
        return errors.New("body must only contain a single JSON value")
    }
  return nil
}

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT