context.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. package cli
  2. import (
  3. "fmt"
  4. "io"
  5. "math"
  6. )
  7. type Context struct {
  8. Id int64
  9. seq uint16
  10. wc io.WriteCloser
  11. params map[string]string
  12. args []string
  13. }
  14. func (ctx *Context) reset(id int64, wc io.WriteCloser) {
  15. ctx.Id = id
  16. ctx.wc = wc
  17. ctx.seq = 0
  18. ctx.args = make([]string, 0)
  19. ctx.params = make(map[string]string)
  20. }
  21. func (ctx *Context) setArgs(args []string) {
  22. ctx.args = args
  23. }
  24. func (ctx *Context) setParam(ps map[string]string) {
  25. ctx.params = ps
  26. }
  27. func (ctx *Context) Bind(v any) (err error) {
  28. return
  29. }
  30. func (ctx *Context) Argument(index int) string {
  31. if index >= len(ctx.args) || index < 0 {
  32. return ""
  33. }
  34. return ctx.args[index]
  35. }
  36. func (ctx *Context) Param(s string) string {
  37. if v, ok := ctx.params[s]; ok {
  38. return v
  39. }
  40. return ""
  41. }
  42. func (ctx *Context) Success(v any) (err error) {
  43. return ctx.send(responsePayload{Type: PacketTypeCommand, Data: v})
  44. }
  45. func (ctx *Context) Error(code int, reason string) (err error) {
  46. return ctx.send(responsePayload{Type: PacketTypeCommand, Code: code, Reason: reason})
  47. }
  48. func (ctx *Context) Close() (err error) {
  49. return ctx.wc.Close()
  50. }
  51. func (ctx *Context) send(res responsePayload) (err error) {
  52. var (
  53. ok bool
  54. buf []byte
  55. marshal encoder
  56. )
  57. if res.Code > 0 {
  58. err = writeFrame(ctx.wc, &Frame{
  59. Feature: Feature,
  60. Type: res.Type,
  61. Seq: ctx.seq,
  62. Flag: FlagComplete,
  63. Error: fmt.Sprintf("ERROR(%d): %s", res.Code, res.Reason),
  64. })
  65. return
  66. }
  67. if res.Data == nil {
  68. buf = OK
  69. goto __END
  70. }
  71. if marshal, ok = res.Data.(encoder); ok {
  72. buf, err = marshal.Marshal()
  73. goto __END
  74. }
  75. buf, err = serialize(res.Data)
  76. __END:
  77. if err != nil {
  78. return
  79. }
  80. offset := 0
  81. chunkSize := math.MaxInt16 - 1
  82. n := len(buf) / chunkSize
  83. for i := 0; i < n; i++ {
  84. if err = writeFrame(ctx.wc, newFrame(res.Type, FlagPortion, ctx.seq, buf[offset:chunkSize+offset])); err != nil {
  85. return
  86. }
  87. offset += chunkSize
  88. }
  89. err = writeFrame(ctx.wc, newFrame(res.Type, FlagComplete, ctx.seq, buf[offset:]))
  90. return
  91. }
  92. func newContext(id int64, wc io.WriteCloser) *Context {
  93. return &Context{
  94. Id: id,
  95. wc: wc,
  96. }
  97. }