...

Source file src/github.com/jackc/pgproto3/v2/sasl_initial_response.go

Documentation: github.com/jackc/pgproto3/v2

     1  package pgproto3
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"errors"
     7  
     8  	"github.com/jackc/pgio"
     9  )
    10  
    11  type SASLInitialResponse struct {
    12  	AuthMechanism string
    13  	Data          []byte
    14  }
    15  
    16  // Frontend identifies this message as sendable by a PostgreSQL frontend.
    17  func (*SASLInitialResponse) Frontend() {}
    18  
    19  // Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message
    20  // type identifier and 4 byte message length.
    21  func (dst *SASLInitialResponse) Decode(src []byte) error {
    22  	*dst = SASLInitialResponse{}
    23  
    24  	rp := 0
    25  
    26  	idx := bytes.IndexByte(src, 0)
    27  	if idx < 0 {
    28  		return errors.New("invalid SASLInitialResponse")
    29  	}
    30  
    31  	dst.AuthMechanism = string(src[rp:idx])
    32  	rp = idx + 1
    33  
    34  	rp += 4 // The rest of the message is data so we can just skip the size
    35  	dst.Data = src[rp:]
    36  
    37  	return nil
    38  }
    39  
    40  // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length.
    41  func (src *SASLInitialResponse) Encode(dst []byte) ([]byte, error) {
    42  	dst, sp := beginMessage(dst, 'p')
    43  
    44  	dst = append(dst, []byte(src.AuthMechanism)...)
    45  	dst = append(dst, 0)
    46  
    47  	dst = pgio.AppendInt32(dst, int32(len(src.Data)))
    48  	dst = append(dst, src.Data...)
    49  
    50  	return finishMessage(dst, sp)
    51  }
    52  
    53  // MarshalJSON implements encoding/json.Marshaler.
    54  func (src SASLInitialResponse) MarshalJSON() ([]byte, error) {
    55  	return json.Marshal(struct {
    56  		Type          string
    57  		AuthMechanism string
    58  		Data          string
    59  	}{
    60  		Type:          "SASLInitialResponse",
    61  		AuthMechanism: src.AuthMechanism,
    62  		Data:          string(src.Data),
    63  	})
    64  }
    65  
    66  // UnmarshalJSON implements encoding/json.Unmarshaler.
    67  func (dst *SASLInitialResponse) UnmarshalJSON(data []byte) error {
    68  	// Ignore null, like in the main JSON package.
    69  	if string(data) == "null" {
    70  		return nil
    71  	}
    72  
    73  	var msg struct {
    74  		AuthMechanism string
    75  		Data          string
    76  	}
    77  	if err := json.Unmarshal(data, &msg); err != nil {
    78  		return err
    79  	}
    80  	dst.AuthMechanism = msg.AuthMechanism
    81  	dst.Data = []byte(msg.Data)
    82  	return nil
    83  }
    84  

View as plain text