github.com/pion/webrtc/v3@v3.2.24/examples/internal/signal/signal.go (about) 1 // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly> 2 // SPDX-License-Identifier: MIT 3 4 // Package signal contains helpers to exchange the SDP session 5 // description between examples. 6 package signal 7 8 import ( 9 "bufio" 10 "bytes" 11 "compress/gzip" 12 "encoding/base64" 13 "encoding/json" 14 "fmt" 15 "io" 16 "io/ioutil" 17 "os" 18 "strings" 19 ) 20 21 // Allows compressing offer/answer to bypass terminal input limits. 22 const compress = false 23 24 // MustReadStdin blocks until input is received from stdin 25 func MustReadStdin() string { 26 r := bufio.NewReader(os.Stdin) 27 28 var in string 29 for { 30 var err error 31 in, err = r.ReadString('\n') 32 if err != io.EOF { 33 if err != nil { 34 panic(err) 35 } 36 } 37 in = strings.TrimSpace(in) 38 if len(in) > 0 { 39 break 40 } 41 } 42 43 fmt.Println("") 44 45 return in 46 } 47 48 // Encode encodes the input in base64 49 // It can optionally zip the input before encoding 50 func Encode(obj interface{}) string { 51 b, err := json.Marshal(obj) 52 if err != nil { 53 panic(err) 54 } 55 56 if compress { 57 b = zip(b) 58 } 59 60 return base64.StdEncoding.EncodeToString(b) 61 } 62 63 // Decode decodes the input from base64 64 // It can optionally unzip the input after decoding 65 func Decode(in string, obj interface{}) { 66 b, err := base64.StdEncoding.DecodeString(in) 67 if err != nil { 68 panic(err) 69 } 70 71 if compress { 72 b = unzip(b) 73 } 74 75 err = json.Unmarshal(b, obj) 76 if err != nil { 77 panic(err) 78 } 79 } 80 81 func zip(in []byte) []byte { 82 var b bytes.Buffer 83 gz := gzip.NewWriter(&b) 84 _, err := gz.Write(in) 85 if err != nil { 86 panic(err) 87 } 88 err = gz.Flush() 89 if err != nil { 90 panic(err) 91 } 92 err = gz.Close() 93 if err != nil { 94 panic(err) 95 } 96 return b.Bytes() 97 } 98 99 func unzip(in []byte) []byte { 100 var b bytes.Buffer 101 _, err := b.Write(in) 102 if err != nil { 103 panic(err) 104 } 105 r, err := gzip.NewReader(&b) 106 if err != nil { 107 panic(err) 108 } 109 res, err := ioutil.ReadAll(r) 110 if err != nil { 111 panic(err) 112 } 113 return res 114 }