Skip to content

Instantly share code, notes, and snippets.

@acidsound
Last active September 4, 2019 07:48
Show Gist options
  • Save acidsound/409aab3f029a8c74b3dc4c188d17ef69 to your computer and use it in GitHub Desktop.
Save acidsound/409aab3f029a8c74b3dc4c188d17ef69 to your computer and use it in GitHub Desktop.
Simple QUIC ECHO Server
package main
import (
"bytes"
"context"
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"io"
"math/big"
"testing"
"github.com/lucas-clemente/quic-go"
)
func generateTLSConfiguration(protos []string) *tls.Config {
key, err := rsa.GenerateKey(rand.Reader, 1024)
if err != nil {
panic(err)
}
template := x509.Certificate{SerialNumber: big.NewInt(1)}
certDER, err := x509.CreateCertificate(rand.Reader, &template, &template, &key.PublicKey, key)
if err != nil {
panic(err)
}
keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})
certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER})
tlsCert, err := tls.X509KeyPair(certPEM, keyPEM)
if err != nil {
panic(err)
}
return &tls.Config{Certificates: []tls.Certificate{tlsCert}, NextProtos: protos}
}
func TestQUIC_LossRecovery(t *testing.T) {
address := "localhost:4242"
go func() {
ln, err := quic.ListenAddr(address, generateTLSConfiguration([]string{"echo"}), &quic.Config{KeepAlive: true})
if err != nil {
t.Error(err)
}
ss, err := ln.Accept(context.Background())
if err != nil {
t.Error(err)
}
stream, err := ss.AcceptStream(context.Background())
if err != nil {
t.Error(err)
}
io.Copy(stream, stream)
}()
session, err := quic.DialAddr(address, &tls.Config{InsecureSkipVerify: true, NextProtos: []string{"echo"}}, nil)
if err != nil {
t.Error(err)
}
stream, err := session.OpenStreamSync(context.Background())
if err != nil {
t.Error(err)
}
for i := 10000; i > 0; i-- {
payload := []byte(fmt.Sprintf("%1024d", i))
n, err := stream.Write(payload)
if err != nil {
t.Error(err)
}
buf := make([]byte, n)
_, err = io.ReadFull(stream, buf)
if err != nil {
t.Error(err)
}
if !bytes.Equal(payload, buf) {
t.Error(errors.New("mismatch"))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment