40 lines
824 B
Go
40 lines
824 B
Go
package networking
|
|
|
|
import (
|
|
"crypto/tls"
|
|
"crypto/x509"
|
|
"encoding/json"
|
|
)
|
|
|
|
type Connection[T any] struct {
|
|
Conn *tls.Conn
|
|
encoder *json.Encoder
|
|
decoder *json.Decoder
|
|
}
|
|
|
|
func NewConnection[T any](netConn *tls.Conn) Connection[T] {
|
|
return Connection[T]{
|
|
Conn: netConn,
|
|
encoder: json.NewEncoder(netConn),
|
|
decoder: json.NewDecoder(netConn),
|
|
}
|
|
}
|
|
|
|
func (c Connection[T]) Send(obj T) {
|
|
if err := c.encoder.Encode(&obj); err != nil {
|
|
panic("Failed encoding data or sending it to connection")
|
|
}
|
|
}
|
|
|
|
func (c Connection[T]) Receive() T {
|
|
var obj T
|
|
if err := c.decoder.Decode(&obj); err != nil {
|
|
panic("Failed decoding data or reading it from connection")
|
|
}
|
|
return obj
|
|
}
|
|
|
|
func (c Connection[T]) GetPeerCertificate() *x509.Certificate {
|
|
state := c.Conn.ConnectionState()
|
|
return state.PeerCertificates[0]
|
|
}
|