exlib.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // Package exlib contains common library code for the examples.
  2. package exlib
  3. import (
  4. "encoding/binary"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "os"
  9. "path/filepath"
  10. "time"
  11. )
  12. var progname = filepath.Base(os.Args[0])
  13. // Before set to 5 minutes; certificates will attempt to auto-update 5
  14. // minutes before they expire.
  15. var Before = 5 * time.Minute
  16. // Err displays a formatting error message to standard error,
  17. // appending the error string, and exits with the status code from
  18. // `exit`, à la err(3).
  19. func Err(exit int, err error, format string, a ...interface{}) {
  20. format = fmt.Sprintf("[%s] %s", progname, format)
  21. format += ": %v\n"
  22. a = append(a, err)
  23. fmt.Fprintf(os.Stderr, format, a...)
  24. os.Exit(exit)
  25. }
  26. // Errx displays a formatted error message to standard error and exits
  27. // with the status code from `exit`, à la errx(3).
  28. func Errx(exit int, format string, a ...interface{}) {
  29. format = fmt.Sprintf("[%s] %s", progname, format)
  30. format += "\n"
  31. fmt.Fprintf(os.Stderr, format, a...)
  32. os.Exit(exit)
  33. }
  34. // Warn displays a formatted error message to standard output,
  35. // appending the error string, à la warn(3).
  36. func Warn(err error, format string, a ...interface{}) (int, error) {
  37. format = fmt.Sprintf("[%s] %s", progname, format)
  38. format += ": %v\n"
  39. a = append(a, err)
  40. return fmt.Fprintf(os.Stderr, format, a...)
  41. }
  42. // Unpack reads a message from an io.Reader.
  43. func Unpack(r io.Reader) ([]byte, error) {
  44. var bl [2]byte
  45. _, err := io.ReadFull(r, bl[:])
  46. if err != nil {
  47. return nil, err
  48. }
  49. n := binary.LittleEndian.Uint16(bl[:])
  50. buf := make([]byte, int(n))
  51. _, err = io.ReadFull(r, buf)
  52. return buf, err
  53. }
  54. const messageMax = 1 << 16
  55. // Pack writes a message to an io.Writer.
  56. func Pack(w io.Writer, buf []byte) error {
  57. if len(buf) > messageMax {
  58. return errors.New("message is too large")
  59. }
  60. var bl [2]byte
  61. binary.LittleEndian.PutUint16(bl[:], uint16(len(buf)))
  62. _, err := w.Write(bl[:])
  63. if err != nil {
  64. return err
  65. }
  66. _, err = w.Write(buf)
  67. return err
  68. }