Standard library / crypto/tls

tls.Conn.Write()

Writes application data to the encrypted transport; may initiate handshake. Handle write count and errors. Expected stdout: '2 Go\n'.

Formal Syntax & Structure

go syntaxgo
func (c *Conn) Write(b []byte) (int, error)

Parameters & Attributes

NameTypeDescription
b[]byteByte buffer for reading or writing.

Return Value

(int, error)

Result of the operation; handle any returned error before using other results.

Working Example

Example Snippetgo
package main
import (  "crypto/ed25519"  "crypto/rand"  "crypto/tls"  "crypto/x509"  "crypto/x509/pkix"  "encoding/pem"  "fmt"  "io"  "math/big"  "net"  "time")
func main() {  sc, cc := configs()  c, s := pair(sc, cc)  defer cleanup(c, s)  n := must(c.Write([]byte("Go")))  b := make([]byte, 2)  must(io.ReadFull(s, b))  fmt.Println(n, string(b))}
// Test fixture: synthetic CA and short-lived certificates, fixed test clock.func configs() (*tls.Config, *tls.Config) {  now := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)  pub, key, e := ed25519.GenerateKey(rand.Reader)  check(e)  ca := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "Test CA"}, NotBefore: now.Add(-time.Hour), NotAfter: now.Add(time.Hour), BasicConstraintsValid: true, IsCA: true, KeyUsage: x509.KeyUsageCertSign}  root := must(x509.ParseCertificate(must(x509.CreateCertificate(rand.Reader, ca, ca, pub, key))))  lp, lk, e := ed25519.GenerateKey(rand.Reader)  check(e)  leaf := &x509.Certificate{SerialNumber: big.NewInt(2), DNSNames: []string{"example.invalid"}, NotBefore: ca.NotBefore, NotAfter: ca.NotAfter, KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth}}  der := must(x509.CreateCertificate(rand.Reader, leaf, root, lp, key))  cert := tls.Certificate{Certificate: [][]byte{der}, PrivateKey: lk, Leaf: must(x509.ParseCertificate(der))}  pool := x509.NewCertPool()  pool.AddCert(root)  server := &tls.Config{Certificates: []tls.Certificate{cert}, MinVersion: tls.VersionTLS13, Time: func() time.Time { return now }, NextProtos: []string{"demo"}}  client := &tls.Config{RootCAs: pool, ServerName: "example.invalid", MinVersion: tls.VersionTLS13, Time: server.Time, NextProtos: []string{"demo"}}  return server, client}
// All connections are bound to an ephemeral IPv4 loopback port and have deadlines.func connect(sc *tls.Config, dial func(string) (net.Conn, error)) (*tls.Conn, *tls.Conn, error) {  l := must(net.Listen("tcp4", "127.0.0.1:0"))  defer l.Close()  type result struct {    c   *tls.Conn    err error  }  done := make(chan result, 1)  go func() {    raw, e := l.Accept()    if e != nil {      done <- result{nil, e}      return    }    check(raw.SetDeadline(time.Now().Add(5 * time.Second)))    s := tls.Server(raw, sc)    e = s.Handshake()    if e != nil {      raw.Close()    }    done <- result{s, e}  }()  c, e := dial(l.Addr().String())  if e != nil {    l.Close()    r := <-done    if r.c != nil {      r.c.NetConn().Close()    }    return nil, nil, e  }  check(c.SetDeadline(time.Now().Add(5 * time.Second)))  r := <-done  if r.err != nil {    c.Close()    return nil, nil, r.err  }  return c.(*tls.Conn), r.c, nil}func pair(sc, cc *tls.Config) (*tls.Conn, *tls.Conn) {  c, s, e := connect(sc, func(addr string) (net.Conn, error) {    return tls.DialWithDialer(&net.Dialer{Timeout: 5 * time.Second}, "tcp4", addr, cc)  })  check(e)  return c, s}func cleanup(c, s *tls.Conn) { c.NetConn().Close(); s.NetConn().Close() }func pemPair() ([]byte, []byte) {  sc, _ := configs()  c := sc.Certificates[0]  return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: c.Certificate[0]}), pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: must(x509.MarshalPKCS8PrivateKey(c.PrivateKey))})}
func must[T any](v T, e error) T {  if e != nil {    panic(e)  }  return v}func check(e error) {  if e != nil {    panic(e)  }}
Go Reference