title: GO dynamic update queries with Gin and PGX
body: <p>I'm trying to build a web service which would receive an HTTP PATCH request to update some fields in a &quot;users&quot; table (so I don't know how many nor which ones have to be updated).</p>
  <p>I decided to work with <a href="https://github.com/gin-gonic/gin" rel="nofollow noreferrer">Gin</a> and because I'm working with Postgres, I'm using <a href="https://github.com/jackc/pgx" rel="nofollow noreferrer">pgx</a>.</p>
  <p>The request...</p>
  <pre><code>PATCH {{protocol}}{{host}}/update-user/USER_ID_XXX HTTP/1.1
  content-type: application/json
  Authorization: Bearer : TOKEN_XXX
  
  {
      &quot;review_count&quot;: 2,
      &quot;rating&quot;: 2.2,
  }
  </code></pre>
  <p>... is handled by the Patch method</p>
  <pre class="lang-golang prettyprint-override"><code>func (handler *userHandler) Patch(c *gin.Context) {
      reqBody := &amp;users.User{}
      err := c.BindJSON(reqBody) &lt;------ BREAKS
      if err != nil {
          c.JSON(http.StatusBadRequest, rest_errors.NewInternalServerError(&quot;JSON Binding Failed while trying to patch user&quot;, err))
          return
      }
      ...
  </code></pre>
  <p>The <code>User</code> struct makes uses of <a href="https://github.com/jackc/pgtype" rel="nofollow noreferrer">pgtypes</a>. This is because, in the context of a <code>GET</code> request, if I retrieve a <code>User</code> from <strong>Postgres</strong> who has a <code>review_count</code> field set to null, i get an error when trying to marshal the result. So the <code>pgtype.Int</code> struct encapsulate the original value, a few other fields and contains a <code>MarshalJSON()</code> function to do the job properly ( <a href="https://github.com/jackc/pgtype/blob/master/int2.go" rel="nofollow noreferrer">see the MarshalJSON function here in pgtype.Int2</a> )</p>
  <p>user_dto.go</p>
  <pre class="lang-golang prettyprint-override"><code>type User struct {
      Id                string        `json:&quot;id&quot;`
      ...
      ReviewCount       pgtype.Int2   `json:&quot;review_count&quot;`
      Rating            float32       `json:&quot;rating&quot;`
      ...
  }
  </code></pre>
  <p>Back to our <code>PATCH</code> request, the problem naturally comes in when I receive a field that is &quot;pgtyped&quot; like <code>review_count</code> .... Gin tries to unmarshal it and fails because it parses an <code>int</code> value and he's asked to put it into the <a href="https://github.com/jackc/pgtype/blob/master/int2.go" rel="nofollow noreferrer">pgtype.Int2</a> struct. So when I call <code>err := c.BindJSON(reqBody)</code> I get this error</p>
  <blockquote>
  <p>&quot;json: cannot unmarshal number into Go struct field
  User.ReviewCount of type pgtype.Int2&quot;</p>
  </blockquote>
  <p>I never had to implement this kind of feature before and I must confess that I know nothing about the &quot;best options&quot; if only I knew one that is working  :D</p>