micro/go-micro · error

failed to marshal request: %w

Error message

failed to marshal request: %w

What it means

callAPI (used by Gemini's non-streaming methods) failed to json.Marshal the request map into the request body. As with the streaming variant, marshaling map[string]any fails only when a value of unsupported type (channel, func, cycle) entered the request construction. The wrapped error pinpoints the offending value.

Source

Thrown at ai/gemini/gemini.go:287

	}
	if err := s.scanner.Err(); err != nil {
		return nil, err
	}
	return nil, io.EOF
}

func (s *streamReader) Close() error {
	if s.closed {
		return nil
	}
	s.closed = true
	return s.body.Close()
}

func (p *Provider) callAPI(ctx context.Context, req map[string]any) (*ai.Response, []map[string]any, error) {
	reqBody, err := json.Marshal(req)
	if err != nil {
		return nil, nil, fmt.Errorf("failed to marshal request: %w", err)
	}

	apiURL := strings.TrimRight(p.opts.BaseURL, "/") +
		"/v1beta/models/" + p.opts.Model + ":generateContent"

	httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, apiURL, bytes.NewReader(reqBody))
	if err != nil {
		return nil, nil, fmt.Errorf("failed to create request: %w", err)
	}

	httpReq.Header.Set("Content-Type", "application/json")
	httpReq.Header.Set("x-goog-api-key", p.opts.APIKey)

	httpResp, err := http.DefaultClient.Do(httpReq)
	if err != nil {
		return nil, nil, fmt.Errorf("API request failed: %w", err)
	}
	defer httpResp.Body.Close()

View on GitHub (pinned to 24529f1404)

Solutions

  1. Inspect the wrapped %w error and remove/convert the non-marshalable value at its source.
  2. Ensure messages, tools, and options contain only JSON-safe types.
  3. Test the request map with json.Marshal in isolation to reproduce and locate the bad field.
  4. Update the library if standard inputs trigger this — it indicates a construction bug.

Example fix

// before
req["systemInstruction"] = someObject
// after
raw, err := json.Marshal(someObject)
if err != nil {
    return nil, nil, fmt.Errorf("systemInstruction not serializable: %w", err)
}
var safe any
_ = json.Unmarshal(raw, &safe)
req["systemInstruction"] = safe
Defensive patterns

Strategy: validation

Validate before calling

if _, err := json.Marshal(req); err != nil {
    return fmt.Errorf("request not serializable: %w", err)
}

Type guard

func jsonSafeMap(m map[string]any) bool {
    b, err := json.Marshal(m)
    return err == nil && json.Valid(b)
}

Try / catch

resp, err := provider.Generate(ctx, req)
if err != nil {
    if strings.Contains(err.Error(), "failed to marshal request") {
        return fmt.Errorf("non-serializable value in request (client bug): %w", err)
    }
    return err
}

Prevention

When it happens

Trigger: Calling a non-streaming Gemini method (Generate/Chat/etc.) when the built req map contains a non-JSON-encodable value.

Common situations: Non-serializable custom types flowing in through message content or options; cyclic references in user data attached to the request; internal library regression.

Understand the failure class

Background: json.Marshal / "failed to marshal" errors in Go: why "unsupported type" happens and how to fix it — this error's family across 22 libraries.

Related errors


AI-assisted analysis of micro/go-micro@24529f1404 (2026-09-01). Data as JSON: /api/errors/c77dc4218a4d2202. Report an issue: GitHub.