trpc.group/trpc-go/trpc-go@v1.0.2/http/serialization_get.go (about)

     1  //
     2  //
     3  // Tencent is pleased to support the open source community by making tRPC available.
     4  //
     5  // Copyright (C) 2023 THL A29 Limited, a Tencent company.
     6  // All rights reserved.
     7  //
     8  // If you have downloaded a copy of the tRPC source code from Tencent,
     9  // please note that tRPC source code is licensed under the  Apache 2.0 License,
    10  // A copy of the Apache 2.0 License is included in this file.
    11  //
    12  //
    13  
    14  package http
    15  
    16  import (
    17  	"errors"
    18  	"net/url"
    19  
    20  	"trpc.group/trpc-go/trpc-go/codec"
    21  )
    22  
    23  func init() {
    24  	codec.RegisterSerializer(codec.SerializationTypeGet, NewGetSerialization(tag))
    25  }
    26  
    27  // NewGetSerialization initializes the get serialized object.
    28  func NewGetSerialization(tag string) codec.Serializer {
    29  
    30  	return &GetSerialization{
    31  		tagname: tag,
    32  	}
    33  }
    34  
    35  // GetSerialization packages kv structure of the http get request.
    36  type GetSerialization struct {
    37  	tagname string
    38  }
    39  
    40  // Unmarshal unpacks kv structure.
    41  func (s *GetSerialization) Unmarshal(in []byte, body interface{}) error {
    42  	values, err := url.ParseQuery(string(in))
    43  	if err != nil {
    44  		return err
    45  	}
    46  	return unmarshalValues(s.tagname, values, body)
    47  }
    48  
    49  // Marshal packages kv structure.
    50  func (s *GetSerialization) Marshal(body interface{}) ([]byte, error) {
    51  	jsonSerializer := codec.GetSerializer(codec.SerializationTypeJSON)
    52  	if jsonSerializer == nil {
    53  		return nil, errors.New("empty json serializer")
    54  	}
    55  	return jsonSerializer.Marshal(body)
    56  }