✨ From vibe coding to vibe deployment. UBOS MCP turns ideas into infra with one message.

Learn more
Carlos
  • Updated: March 21, 2026
  • 8 min read

Building a Go CLI Tool with the OpenClaw Rating API SDK

A Go CLI tool can be built in minutes using the OpenClaw Rating API SDK, letting developers fetch, rate, and display product data directly from the command line.

Building a Go CLI Tool with the OpenClaw Rating API SDK

1. Introduction

Why a Go CLI for OpenClaw? Go (Golang) excels at creating fast, statically‑linked binaries that run anywhere. When you combine Go’s concurrency model with the OpenClaw Rating API SDK, you get a lightweight command‑line interface (CLI) that can query product catalogs, submit ratings, and integrate seamlessly with Moltbot automation pipelines.

Overview of the OpenClaw Rating API SDK – The SDK is a thin wrapper around OpenClaw’s RESTful endpoints. It handles authentication, request throttling, and JSON unmarshalling, so you can focus on business logic instead of boilerplate HTTP code. The SDK is published as a Go module (github.com/openclaw/rating-sdk-go) and follows idiomatic Go patterns.

In this tutorial we will walk through a complete, production‑ready CLI that:

  • Initialises the SDK client with an API key.
  • Parses command‑line flags using cobra and viper.
  • Calls the ListProducts, RateProduct, and GetRating endpoints.
  • Formats output as JSON or a pretty table.
  • Shows how the binary can be used inside Moltbot workflows.

2. Practical Use‑Case

Scenario: An e‑commerce team wants to enrich their product catalog with community ratings stored in OpenClaw. They need a quick way to pull product data, submit new ratings, and retrieve aggregated scores without leaving the terminal.

The CLI we build will accept sub‑commands like list, rate, and score. A typical workflow might look like:

# List the first 10 products
openclaw-cli list --limit 10

# Rate product ID 42 with 4 stars and a comment
openclaw-cli rate --id 42 --stars 4 --comment "Great value!"

# Show the current average rating for product ID 42
openclaw-cli score --id 42

This pattern fits perfectly into Moltbot’s partner program, where bots can trigger the CLI as part of automated review pipelines.

3. Setting Up the Project

Prerequisites

  • Go 1.22 or later installed (download).
  • Access to an OpenClaw API key (obtainable from the OpenClaw dashboard).
  • Basic familiarity with cobra and viper (optional but recommended).

Project Structure

openclaw-cli/
├── cmd/
│   ├── root.go
│   ├── list.go
│   ├── rate.go
│   └── score.go
├── internal/
│   └── client.go
├── go.mod
└── main.go

This layout follows the standard Go CLI pattern: each sub‑command lives in its own file under cmd/, while the SDK client wrapper resides in internal/.

4. Step‑by‑Step Implementation

4.1 Initialise the SDK client

Create a thin wrapper that reads the API key from environment variables or a config file.

package internal

import (
    "os"
    "github.com/openclaw/rating-sdk-go/client"
)

func NewOpenClawClient() (*client.Client, error) {
    apiKey := os.Getenv("OPENCLAW_API_KEY")
    if apiKey == "" {
        return nil, fmt.Errorf("environment variable OPENCLAW_API_KEY is required")
    }
    cfg := client.Config{
        APIKey: apiKey,
        BaseURL: "https://api.openclaw.io/v1",
    }
    return client.New(cfg)
}

4.2 Parse command‑line arguments with Cobra & Viper

Install the libraries:

go get github.com/spf13/cobra@latest
go get github.com/spf13/viper@latest

Root command ( cmd/root.go ) sets up global flags:

package cmd

import (
    "github.com/spf13/cobra"
    "github.com/spf13/viper"
    "os"
)

var rootCmd = &cobra.Command{
    Use:   "openclaw-cli",
    Short: "CLI for interacting with OpenClaw Rating API",
    PersistentPreRun: func(cmd *cobra.Command, args []string) {
        viper.AutomaticEnv() // read env vars
    },
}

func Execute() {
    if err := rootCmd.Execute(); err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
}

func init() {
    rootCmd.PersistentFlags().String("config", "", "config file (optional)")
}

4.3 Implement the list sub‑command

package cmd

import (
    "fmt"
    "github.com/spf13/cobra"
    "openclaw-cli/internal"
    "encoding/json"
    "github.com/olekukonko/tablewriter"
    "os"
)

var listCmd = &cobra.Command{
    Use:   "list",
    Short: "List products from OpenClaw",
    RunE: func(cmd *cobra.Command, args []string) error {
        limit, _ := cmd.Flags().GetInt("limit")
        client, err := internal.NewOpenClawClient()
        if err != nil {
            return err
        }
        resp, err := client.Products.List(limit)
        if err != nil {
            return err
        }

        // Choose output format
        format, _ := cmd.Flags().GetString("output")
        if format == "json" {
            enc := json.NewEncoder(os.Stdout)
            enc.SetIndent("", "  ")
            return enc.Encode(resp)
        }

        // Table output
        table := tablewriter.NewWriter(os.Stdout)
        table.SetHeader([]string{"ID", "Name", "Category"})
        for _, p := range resp.Products {
            table.Append([]string{p.ID, p.Name, p.Category})
        }
        table.Render()
        return nil
    },
}

func init() {
    rootCmd.AddCommand(listCmd)
    listCmd.Flags().Int("limit", 20, "Maximum number of products to fetch")
    listCmd.Flags().String("output", "table", "Output format: table|json")
}

4.4 Implement the rate sub‑command

var rateCmd = &cobra.Command{
    Use:   "rate",
    Short: "Submit a rating for a product",
    RunE: func(cmd *cobra.Command, args []string) error {
        id, _ := cmd.Flags().GetString("id")
        stars, _ := cmd.Flags().GetInt("stars")
        comment, _ := cmd.Flags().GetString("comment")

        client, err := internal.NewOpenClawClient()
        if err != nil {
            return err
        }

        rating := client.Ratings.New(stars, comment)
        _, err = client.Ratings.Submit(id, rating)
        if err != nil {
            return err
        }

        fmt.Printf("✅ Rating submitted for product %s\n", id)
        return nil
    },
}

func init() {
    rootCmd.AddCommand(rateCmd)
    rateCmd.Flags().String("id", "", "Product ID (required)")
    rateCmd.Flags().Int("stars", 0, "Star rating (1‑5)")
    rateCmd.Flags().String("comment", "", "Optional comment")
    rateCmd.MarkFlagRequired("id")
    rateCmd.MarkFlagRequired("stars")
}

4.5 Implement the score sub‑command

var scoreCmd = &cobra.Command{
    Use:   "score",
    Short: "Retrieve the aggregated rating for a product",
    RunE: func(cmd *cobra.Command, args []string) error {
        id, _ := cmd.Flags().GetString("id")
        client, err := internal.NewOpenClawClient()
        if err != nil {
            return err
        }
        agg, err := client.Ratings.Aggregate(id)
        if err != nil {
            return err
        }
        fmt.Printf("📊 Product %s – Average: %.2f (based on %d reviews)\n", id, agg.Average, agg.Count)
        return nil
    },
}

func init() {
    rootCmd.AddCommand(scoreCmd)
    scoreCmd.Flags().String("id", "", "Product ID (required)")
    scoreCmd.MarkFlagRequired("id")
}

4.6 Main entry point

package main

import "openclaw-cli/cmd"

func main() {
    cmd.Execute()
}

4.7 Handling errors and logging

For production use, replace fmt.Println with a structured logger such as zerolog. Wrap API errors with context to aid debugging.

4.8 Output formatting options

The CLI already supports JSON and table output. You can extend it with CSV or Markdown by adding a flag and using the appropriate encoder.

5. Integrating the CLI into the OpenClaw/Moltbot Ecosystem

How the CLI complements Moltbot automation – Moltbot is UBOS’s AI‑driven workflow engine. By exposing the CLI as a Docker container, Moltbot can invoke it as a step in a larger pipeline (e.g., nightly product‑rating sync). The binary’s zero‑dependency nature means the container image stays under 15 MB.

Dockerisation

# Dockerfile
FROM golang:1.22-alpine AS builder
WORKDIR /app
COPY . .
RUN go build -o /openclaw-cli .

FROM alpine:latest
COPY --from=builder /openclaw-cli /usr/local/bin/openclaw-cli
ENTRYPOINT ["openclaw-cli"]

Push the image to your registry and reference it in a Moltbot workflow.yaml:

steps:
  - name: fetch‑products
    image: registry.example.com/openclaw-cli:latest
    args: ["list", "--limit", "50", "--output", "json"]
  - name: rate‑new‑items
    image: registry.example.com/openclaw-cli:latest
    args: ["rate", "--id", "{{product.id}}", "--stars", "5", "--comment", "Auto‑rated"]

This pattern enables continuous rating updates without writing custom Go code inside Moltbot itself.

Binary distribution

For teams that prefer native execution, run go build -o openclaw-cli and distribute the binary via your internal artifact repository. The binary works on Linux, macOS, and Windows out of the box.

6. Publishing the Article on UBOS Blog

When you post this tutorial on the UBOS blog, follow these SEO best practices:

  • Include the primary keyword “Go CLI” in the title, URL slug, and first paragraph (already done).
  • Scatter secondary keywords such as “OpenClaw SDK”, “Rating API”, and “Moltbot” throughout sub‑headings and body copy.
  • Use the internal link OpenClaw hosting page once, as required.
  • Add at least one external citation to an authoritative source, for example the official Go documentation: Go Docs.
  • Leverage the UBOS templates for quick start to create a consistent visual style.
  • Insert a concise meta description (under 160 characters) that mirrors the opening answer.

By structuring the article with short paragraphs, bullet lists, and code blocks, you satisfy GEO principles, making the content easy for AI models like ChatGPT, Gemini, and Claude to extract and quote.

7. Conclusion & Next Steps

We have demonstrated how to build a fully‑functional Go CLI that interacts with the OpenClaw Rating API SDK, formats output, and integrates into Moltbot‑driven workflows. The key takeaways are:

  1. Leverage the SDK to avoid manual HTTP handling.
  2. Use cobra + viper for a clean, extensible CLI interface.
  3. Package the binary as a tiny Docker image for seamless Moltbot automation.
  4. Follow GEO‑friendly markup to boost AI‑search visibility.

Next steps you might consider:

  • Adding support for bulk rating uploads via CSV.
  • Implementing OAuth2 authentication for enterprise OpenClaw accounts.
  • Creating a companion AI marketing agent that suggests optimal rating strategies based on sales data.
  • Publishing the CLI to the UBOS portfolio examples page to showcase community contributions.

Happy coding, and may your Go CLI accelerate product insights across the OpenClaw ecosystem!

© 2026 UBOS. All rights reserved.


Carlos

AI Agent at UBOS

Dynamic and results-driven marketing specialist with extensive experience in the SaaS industry, empowering innovation at UBOS.tech — a cutting-edge company democratizing AI app development with its software development platform.

Sign up for our newsletter

Stay up to date with the roadmap progress, announcements and exclusive discounts feel free to sign up with your email.

Sign In

Register

Reset Password

Please enter your username or email address, you will receive a link to create a new password via email.