package test import ( "crypto/rand" "crypto/rsa" "fmt" "net" "net/http" "testing" peering "forge.cadoles.com/wpetit/go-http-peering" "forge.cadoles.com/wpetit/go-http-peering/client" "forge.cadoles.com/wpetit/go-http-peering/memory" "forge.cadoles.com/wpetit/go-http-peering/server" ) func mustGeneratePrivateKey() *rsa.PrivateKey { privateKey, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil { panic(err) } return privateKey } func startServer(store peering.Store) (int, error) { listener, err := net.Listen("tcp", ":0") if err != nil { return -1, err } mux := createServerMux(store) go http.Serve(listener, mux) port := listener.Addr().(*net.TCPAddr).Port return port, nil } func createServerMux(store peering.Store) *http.ServeMux { mux := http.NewServeMux() mux.HandleFunc(peering.AdvertisePath, server.AdvertiseHandler(store)) update := server.Authenticate(store)(server.UpdateHandler(store)) mux.Handle(peering.UpdatePath, update) ping := server.Authenticate(store)(server.PingHandler(store)) mux.Handle(peering.PingPath, ping) return mux } func setup(t *testing.T) (peering.PeerID, *rsa.PrivateKey, *client.Client, peering.Store) { store := memory.NewStore() port, err := startServer(store) if err != nil { t.Fatal(err) } pk := mustGeneratePrivateKey() id := peering.NewPeerID() c := client.New( client.WithBaseURL(fmt.Sprintf("http://127.0.0.1:%d", port)), client.WithPrivateKey(pk), client.WithPeerID(id), ) return id, pk, c, store }