3

There is a service written in golang, using gin-gonic framework.

I only ever want to support application/json as a mime-type and it would be great if it always be in UTF-8. The business logic of the service might break if it will get values in different encodings.

Is it a good idea to write a custom middleware that checks if Content-Type header has value "application/json; charset=utf-8" and returns some 4xx status in case it is not?

UPDATE: Just found out that ctx.ContentType() doesn't return charset part of the header. Is there a way to get it?

dmigo
  • 2,849
  • 4
  • 41
  • 62
  • 2
    Yes it is good. – Roman Kiselenko Dec 23 '19 at 13:28
  • 1
    Hi! For the sake of future visitors, could you perhaps change the reference you're using, since (currently) it's a redirect to something behind a password-protected website at Ohio University? Are you directly pointing to the source code itself? If so, perhaps you were looking for something like https://github.com/gin-gonic/gin/blob/d4a64265f21993368c90602c18e778bf04ef36db/context.go#L817 ? Or maybe a link to some documentation page? Anyway, whichever might be the case, I believe that it would best to get a link that anyone can use _and_ possibly copy the paragraph explaining `ContentType()`. – Gwyneth Llewelyn Aug 02 '23 at 21:01
  • Thanks for raising! the link is up to date now. – dmigo Aug 03 '23 at 16:46

1 Answers1

4

Nothing prevents you from simply looking at the "Content-Type" http header directly, to the tune of ctx.Request.Header.Get("Content-Type").

The helper ContentType method is provided by gin-gonic especially for the rather common case of querying the "unadulterated" mime type of incoming data without too much hassle.

rlandster
  • 7,294
  • 14
  • 58
  • 96
oakad
  • 6,945
  • 1
  • 22
  • 31
  • Could you also add an answer to the main part of the question, so that I could accept the answer? – dmigo Dec 23 '19 at 14:43
  • I don't know what your application is about. In general, it seems you're talking about standard "Accept-Charset"/406 mechanism, which you can read about elsewhere. – oakad Dec 23 '19 at 15:36
  • Not exactly. [Accept-Charset](https://developer.mozilla.org/en-US/docs/Web/HTTP/headers/Accept-Charset) tells what charset does the client expect to get in the response. I'd rather validate that client sends everything as charset=utf-8 in request. – dmigo Dec 23 '19 at 16:03