Membuat REST API Sederhana dengan Go dan Mengintegrasikannya dengan OpenClaw


Go dapat digunakan untuk membuat REST API sederhana tanpa framework tambahan. Untuk kebutuhan internal, kita cukup menggunakan package bawaan net/http.

Pada tutorial ini kita akan membuat REST API sederhana menggunakan Go dengan dua endpoint:

GET  /status
POST /post

Kemudian REST API tersebut akan diintegrasikan ke OpenClaw menggunakan custom tool:

rest_api_custom

Arsitektur yang digunakan:

Raspberry Pi
12.12.12.254
       │
       │ OpenClaw
       │
       ▼
10.10.10.178
       │
       │ REST API
       ▼
    Go Server

1. Membuat Project Go

Pada server 10.10.10.178, buat folder project:

mkdir rest-api
cd rest-api

Buat module Go:

go mod init rest-api

REST API ini tidak membutuhkan dependency eksternal.


2. Membuat REST API

Buat file:

nano main.go

Masukkan kode berikut:

package main

import (
	"encoding/json"
	"log"
	"net/http"
)

type Response struct {
	OK      bool   `json:"ok"`
	Message string `json:"message"`
}

func writeJSON(w http.ResponseWriter, status int, response Response) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)

	json.NewEncoder(w).Encode(response)
}

func statusHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		writeJSON(w, http.StatusMethodNotAllowed, Response{
			OK:      false,
			Message: "method not allowed",
		})
		return
	}

	writeJSON(w, http.StatusOK, Response{
		OK:      true,
		Message: "hello world",
	})
}

func postHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		writeJSON(w, http.StatusMethodNotAllowed, Response{
			OK:      false,
			Message: "method not allowed",
		})
		return
	}

	writeJSON(w, http.StatusOK, Response{
		OK:      true,
		Message: "post oke",
	})
}

func main() {
	http.HandleFunc("/status", statusHandler)
	http.HandleFunc("/post", postHandler)

	log.Println("REST API running on 0.0.0.0:8765")

	err := http.ListenAndServe("0.0.0.0:8765", nil)
	if err != nil {
		log.Fatal(err)
	}
}

Kode tersebut hanya menggunakan standard library Go:

net/http
encoding/json
log

Tidak diperlukan Gin, Fiber, Echo, atau framework lainnya.


3. Menjalankan REST API

Jalankan:

go run main.go

Jika berhasil:

REST API running on 0.0.0.0:8765

API dapat diakses melalui:

http://10.10.10.178:8765

4. Test Endpoint GET

Dari Raspberry Pi:

curl http://10.10.10.178:8765/status

Response:

{
  "ok": true,
  "message": "hello world"
}

Endpoint yang digunakan:

GET /status

5. Test Endpoint POST

Jalankan:

curl -X POST http://10.10.10.178:8765/post

Response:

{
  "ok": true,
  "message": "post oke"
}

Endpoint yang digunakan:

POST /post

Dengan demikian REST API sudah memiliki dua endpoint sederhana:

GET  /status → hello world
POST /post   → post oke

6. Membuat Binary Go

Go dapat mengompilasi aplikasi menjadi satu binary.

Jalankan:

go build -o rest-api

Kemudian:

./rest-api

Binary tersebut dapat dijalankan tanpa memerlukan source code ketika deployment.


7. Membuat Plugin OpenClaw

Sekarang kita membuat custom tool untuk mengakses REST API.

Pada Raspberry Pi:

cd ~/.openclaw/plugins

Buat plugin:

openclaw plugins init rest-api-custom --name "REST API Custom"

Masuk ke folder:

cd ~/.openclaw/plugins/rest-api-custom

Buka file:

nano src/index.ts

Ganti isinya dengan:

import { Type } from "typebox";
import { defineToolPlugin } from "openclaw/plugin-sdk/tool-plugin";

const REST_API_URL = "http://10.10.10.178:8765";

async function requestApi(
  method: "GET" | "POST",
  endpoint: "/status" | "/post",
) {
  const response = await fetch(
    `${REST_API_URL}${endpoint}`,
    {
      method,
      headers: {
        Accept: "application/json",
      },
    },
  );

  const text = await response.text();

  let data: unknown;

  try {
    data = JSON.parse(text);
  } catch {
    data = {
      raw: text,
    };
  }

  if (!response.ok) {
    throw new Error(
      `REST API error ${response.status}: ${text}`,
    );
  }

  return data;
}

export default defineToolPlugin({
  id: "rest-api-custom",

  name: "REST API Custom",

  description:
    "Call the internal custom REST API.",

  tools: (tool) => [
    tool({
      name: "rest_api_custom",

      description:
        "Call the custom REST API. GET /status returns hello world. POST /post returns post oke.",

      parameters: Type.Object({
        method: Type.Union([
          Type.Literal("GET"),
          Type.Literal("POST"),
        ]),

        endpoint: Type.Union([
          Type.Literal("/status"),
          Type.Literal("/post"),
        ]),
      }),

      execute: async ({
        method,
        endpoint,
      }) => {
        return await requestApi(
          method,
          endpoint,
        );
      },
    }),
  ],
});

Plugin ini hanya memiliki satu tool:

rest_api_custom

Tool tersebut dapat melakukan dua jenis request:

GET  /status
POST /post

8. Build dan Validasi Plugin

Masuk ke folder plugin:

cd ~/.openclaw/plugins/rest-api-custom

Install dependency:

npm install

Build:

npm run plugin:build

Kemudian validasi:

npm run plugin:validate

Jika berhasil:

Plugin rest-api-custom is valid.

9. Install Plugin ke OpenClaw

Install plugin lokal:

openclaw plugins install ~/.openclaw/plugins/rest-api-custom

Setelah berhasil, periksa:

openclaw plugins list

Plugin harus muncul sebagai:

REST API Custom
rest-api-custom
enabled

10. Menambahkan Tool ke Agent Rocky

Plugin yang sudah aktif belum otomatis tersedia untuk agent.

Tambahkan rest_api_custom ke allowlist agent:

openclaw config set agents.entries.rocky.tools.allow[5] rest_api_custom

Kemudian periksa:

openclaw config get agents.entries.rocky.tools.allow

Pastikan rest_api_custom sudah terdapat di dalam daftar tool.

Jika agent Rocky sebelumnya memiliki lima tool:

message
browser
web_search
memory_search
memory_get

hasil akhirnya menjadi:

[
  "message",
  "browser",
  "web_search",
  "memory_search",
  "memory_get",
  "rest_api_custom"
]

Dengan demikian rest_api_custom menjadi satu-satunya custom REST API tool yang diberikan kepada agent.


11. Restart OpenClaw Gateway

Setelah konfigurasi tool berubah:

openclaw gateway restart

Setelah Gateway aktif kembali, tool rest_api_custom dapat digunakan oleh agent.


12. Test REST API dari OpenClaw

Untuk menguji endpoint GET, gunakan instruksi:

Gunakan rest_api_custom dengan GET /status.

OpenClaw akan melakukan:

GET http://10.10.10.178:8765/status

Response:

{
  "ok": true,
  "message": "hello world"
}

Untuk menguji POST:

Gunakan rest_api_custom dengan POST /post.

OpenClaw akan melakukan:

POST http://10.10.10.178:8765/post

Response:

{
  "ok": true,
  "message": "post oke"
}

13. Arsitektur Akhir

Setelah semuanya selesai, alurnya menjadi:

                     Raspberry Pi
                      12.12.12.254
                           │
                           ▼
                      ┌─────────┐
                      │ OpenClaw│
                      │  Agent  │
                      └────┬────┘
                           │
                   rest_api_custom
                           │
                           │ HTTP
                           ▼
                     10.10.10.178
                           │
                           ▼
                    ┌─────────────┐
                    │ Go REST API │
                    └──────┬──────┘
                           │
                ┌──────────┴──────────┐
                │                     │
             GET /status          POST /post
                │                     │
                ▼                     ▼
          "hello world"          "post oke"

Kesimpulan

REST API sederhana tidak membutuhkan framework besar. Dengan Go standard library, kita dapat membuat HTTP API yang ringan dan dapat dikompilasi menjadi satu binary.

API yang dibuat hanya memiliki:

GET  /status
POST /post

Sedangkan OpenClaw mengakses API tersebut melalui satu custom tool:

rest_api_custom

Tool tersebut kemudian ditambahkan secara eksplisit ke allowlist agent sehingga agent hanya mendapatkan akses ke fungsi REST API yang memang dibutuhkan.

Struktur ini juga mudah dikembangkan. Jika nantinya membutuhkan endpoint tambahan, endpoint baru dapat ditambahkan pada server Go dan kemudian didaftarkan pada rest_api_custom.

Leave a Reply

Your email address will not be published. Required fields are marked *