gtsocial-umbx

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README | LICENSE

sasl_initial_response.go (2058B)


      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 {
     42 	dst = append(dst, 'p')
     43 	sp := len(dst)
     44 	dst = pgio.AppendInt32(dst, -1)
     45 
     46 	dst = append(dst, []byte(src.AuthMechanism)...)
     47 	dst = append(dst, 0)
     48 
     49 	dst = pgio.AppendInt32(dst, int32(len(src.Data)))
     50 	dst = append(dst, src.Data...)
     51 
     52 	pgio.SetInt32(dst[sp:], int32(len(dst[sp:])))
     53 
     54 	return dst
     55 }
     56 
     57 // MarshalJSON implements encoding/json.Marshaler.
     58 func (src SASLInitialResponse) MarshalJSON() ([]byte, error) {
     59 	return json.Marshal(struct {
     60 		Type          string
     61 		AuthMechanism string
     62 		Data          string
     63 	}{
     64 		Type:          "SASLInitialResponse",
     65 		AuthMechanism: src.AuthMechanism,
     66 		Data:          string(src.Data),
     67 	})
     68 }
     69 
     70 // UnmarshalJSON implements encoding/json.Unmarshaler.
     71 func (dst *SASLInitialResponse) UnmarshalJSON(data []byte) error {
     72 	// Ignore null, like in the main JSON package.
     73 	if string(data) == "null" {
     74 		return nil
     75 	}
     76 
     77 	var msg struct {
     78 		AuthMechanism string
     79 		Data          string
     80 	}
     81 	if err := json.Unmarshal(data, &msg); err != nil {
     82 		return err
     83 	}
     84 	dst.AuthMechanism = msg.AuthMechanism
     85 	dst.Data = []byte(msg.Data)
     86 	return nil
     87 }