github.com/lastbackend/toolkit@v0.0.0-20241020043710-cafa37b95aad/pkg/server/http/marshaler.go (about) 1 /* 2 Copyright [2014] - [2023] The Last.Backend authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package http 18 19 import ( 20 "github.com/lastbackend/toolkit/pkg/server/http/marshaler" 21 "github.com/lastbackend/toolkit/pkg/server/http/marshaler/formpb" 22 "github.com/lastbackend/toolkit/pkg/server/http/marshaler/jsonpb" 23 "google.golang.org/protobuf/encoding/protojson" 24 ) 25 26 const ( 27 ContentTypeForm = "application/x-www-form-urlencoded" 28 ContentTypeJSON = "application/json" 29 ) 30 31 var ( 32 DefaultMarshaler = &jsonpb.JSONPb{ 33 MarshalOptions: defaultMarshalOptions, 34 UnmarshalOptions: defaultUnmarshalOptions, 35 } 36 ) 37 38 var ( 39 defaultMarshalOptions = protojson.MarshalOptions{ 40 EmitUnpopulated: true, // Include fields with default values in the JSON output 41 UseProtoNames: true, // Use original proto field names (e.g., 'start_date') instead of CamelCase (e.g., 'StartDate') 42 } 43 defaultUnmarshalOptions = protojson.UnmarshalOptions{ 44 DiscardUnknown: true, // Ignores unknown fields during deserialization 45 } 46 ) 47 48 func GetMarshalerMap() map[string]marshaler.Marshaler { 49 return map[string]marshaler.Marshaler{ 50 ContentTypeJSON: &jsonpb.JSONPb{ 51 MarshalOptions: defaultMarshalOptions, 52 UnmarshalOptions: defaultUnmarshalOptions, 53 }, 54 ContentTypeForm: &formpb.FORMPb{ 55 MarshalOptions: defaultMarshalOptions, 56 UnmarshalOptions: defaultUnmarshalOptions, 57 }, 58 } 59 }