Content-Type

This commit is contained in:
2024-10-20 18:13:07 +08:00
parent 9ac6370ecb
commit e5a32bc05a
7 changed files with 95 additions and 44 deletions

View File

@ -77,8 +77,9 @@ func (v localCommandRpcServer) SendCommand(ctx context.Context, argument *proto.
return nil, err
} else {
return &proto.CommandReturn{
Status: int32(cc.statusCode),
Payload: cc.responseBody,
Status: int32(cc.statusCode),
ContentType: cc.contentType,
Payload: cc.responseBody,
}, nil
}
}

View File

@ -9,11 +9,29 @@ type CommandCtx struct {
requestBody []byte
responseBody []byte
statusCode int
contentType string
statusCode int
values sync.Map
}
func (c *CommandCtx) Values() map[string]any {
duplicate := make(map[string]any)
c.values.Range(func(key, value any) bool {
duplicate[key.(string)] = value
return true
})
return duplicate
}
func (c *CommandCtx) ValueOrElse(key string, defaultValue any) any {
val, _ := c.values.Load(key)
if val == nil {
return defaultValue
}
return val
}
func (c *CommandCtx) Value(key string, newValue ...any) any {
if len(newValue) > 0 {
c.values.Store(key, newValue[0])
@ -30,8 +48,9 @@ func (c *CommandCtx) ReadJSON(out any) error {
return json.Unmarshal(c.requestBody, out)
}
func (c *CommandCtx) Write(data []byte, statusCode ...int) error {
func (c *CommandCtx) Write(data []byte, contentType string, statusCode ...int) error {
c.responseBody = data
c.contentType = contentType
if len(statusCode) > 0 {
c.statusCode = statusCode[0]
}
@ -43,5 +62,5 @@ func (c *CommandCtx) JSON(data any, statusCode ...int) error {
if err != nil {
return err
}
return c.Write(raw, statusCode...)
return c.Write(raw, "application/json", statusCode...)
}

View File

@ -26,7 +26,7 @@ func TestHandleCommand(t *testing.T) {
}
err = conn.AddCommand("say.hi", "all", nil, func(ctx *nex.CommandCtx) error {
return ctx.Write([]byte("Hello, World!"), http.StatusOK)
return ctx.Write([]byte("Hello, World!"), "text/plain", http.StatusOK)
})
if err != nil {
t.Fatal(fmt.Errorf("unable to add command: %v", err))
@ -34,7 +34,13 @@ func TestHandleCommand(t *testing.T) {
}
err = conn.AddCommand("echo", "all", nil, func(ctx *nex.CommandCtx) error {
t.Log("Received command: ", string(ctx.Read()))
return ctx.Write(ctx.Read(), http.StatusOK)
return ctx.Write(ctx.Read(), "text/plain", http.StatusOK)
})
err = conn.AddCommand("echo.details", "all", nil, func(ctx *nex.CommandCtx) error {
return ctx.JSON(map[string]any{
"values": ctx.Values(),
"body": ctx.Read(),
}, http.StatusOK)
})
if err != nil {
t.Fatal(fmt.Errorf("unable to add command: %v", err))