@@ -30,6 +30,7 @@ type Generator struct {
3030 defaultOperations []* ir.Operation // Operations without an operation group.
3131 operationGroups []* ir.OperationGroup
3232 webhooks []* ir.Operation
33+ mediaTypes map [ir.ContentType ]* ir.MediaType
3334 securities map [string ]* ir.Security
3435 tstorage * tstorage
3536 errType * ir.Response
@@ -98,6 +99,7 @@ func NewGenerator(spec *ogen.Spec, opts Options) (*Generator, error) {
9899 servers : nil ,
99100 operations : nil ,
100101 webhooks : nil ,
102+ mediaTypes : map [ir.ContentType ]* ir.MediaType {},
101103 securities : map [string ]* ir.Security {},
102104 tstorage : newTStorage (),
103105 errType : nil ,
@@ -187,6 +189,21 @@ func (g *Generator) makeOps(ops []*openapi.Operation) error {
187189 return err
188190 }
189191
192+ // Collect all media types used in responses to generate constants
193+ for _ , response := range op .Responses .StatusCode {
194+ for contentType := range response .Contents {
195+ if _ , ok := g .mediaTypes [contentType ]; ! ok {
196+ constantName , err := pascalNonEmpty (string (contentType ))
197+ if err != nil {
198+ return errors .Wrap (err , "gather media types" )
199+ }
200+ g .mediaTypes [contentType ] = & ir.MediaType {
201+ Name : constantName ,
202+ Value : contentType ,
203+ }
204+ }
205+ }
206+ }
190207 g .operations = append (g .operations , op )
191208 }
192209
@@ -282,6 +299,12 @@ func sortOperations(ops []*ir.Operation) {
282299 })
283300}
284301
302+ func sortMediaTypes (types []* ir.MediaType ) {
303+ slices .SortStableFunc (types , func (a , b * ir.MediaType ) int {
304+ return strings .Compare (a .Name , b .Name )
305+ })
306+ }
307+
285308func groupOperations (ops []* ir.Operation ) (
286309 defaultOperations []* ir.Operation ,
287310 operationGroups []* ir.OperationGroup ,
@@ -320,6 +343,16 @@ func (g *Generator) Operations() []*ir.Operation {
320343 return g .operations
321344}
322345
346+ // MediaTypes returns generated media type constants.
347+ func (g * Generator ) MediaTypes () []* ir.MediaType {
348+ mediaTypesSorted := make ([]* ir.MediaType , 0 , len (g .mediaTypes ))
349+ for _ , mt := range g .mediaTypes {
350+ mediaTypesSorted = append (mediaTypesSorted , mt )
351+ }
352+ sortMediaTypes (mediaTypesSorted )
353+ return mediaTypesSorted
354+ }
355+
323356// Webhooks returns generated webhooks.
324357func (g * Generator ) Webhooks () []* ir.Operation {
325358 return g .webhooks
0 commit comments