Pesquisar

Discussão (0)1
Entre ou crie uma conta para continuar
Artigo
· Out. 7 31min de leitura

Bringing It All Together: Go, GORM, and InterSystems IRIS in Action

Since we reached two important milestones for Go developers working with InterSystems IRIS:

Now it’s time to see everything working together.

To demonstrate how easily Go developers can adopt InterSystems IRIS, I took an existing production-grade open-source project — the RealWorld Example App — which showcases a full-stack Medium.com-style clone implemented with Go Fiber, GORM, and SQLite.

RealWorld Example App

With just a few configuration tweaks, I swapped out SQLite for gorm-iris, keeping everything else unchanged. The result?
A fully functional Go + Fiber application powered by InterSystems IRIS — no code rewrites, no ORM gymnastics, just a different database backend.

You can find the complete working demo here: github.com/caretdev/golang-fiber-iris-realworld-example-app

Getting Started

Let’s run the demo project.


1. Clone the Project

git clone git@github.com:caretdev/golang-fiber-iris-realworld-example-app.git 
cd golang-fiber-iris-realworld-example-app

2. Download Dependencies and Generate Swagger Docs

Install Go dependencies and generate the API documentation:

go mod download 
go install github.com/swaggo/swag/cmd/swag@latest 
go generate .

This will:

  • Download all required Go modules.
  • Install the swag tool for generating Swagger documentation.
  • Execute the Go generate command, which rebuilds Swagger definitions from annotations in the codebase.

After running this, you should see the generated documentation files under the docs/ directory.

3. Database Setup and Testing

The project includes a db.go file, which defines the logic for initializing a database connection.
To simplify testing and ensure a clean environment, we’re using testcontainers-iris-go — it spins up a fresh InterSystems IRIS container for each test run.

This means every test starts with an empty, isolated IRIS instance — ideal for reliable automated testing.

Here’s the core part of the code that makes it work:

var container *iriscontainer.IRISContainer

func TestDB(useContainer bool) *gorm.DB {
	var err error
	var connectionString = "iris://_SYSTEM:SYS@localhost:1972/USER"
	if useContainer {
		options := []testcontainers.ContainerCustomizer{
			iriscontainer.WithNamespace("TEST"),
			iriscontainer.WithUsername("testuser"),
			iriscontainer.WithPassword("testpassword"),
		}
		ctx := context.Background()
		container, err = iriscontainer.RunContainer(ctx, options...)
		if err != nil {
			log.Println("Failed to start container:", err)
			os.Exit(1)
		}
		connectionString = container.MustConnectionString(ctx)
		fmt.Println("Container started: ", connectionString)
	}

	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold: time.Second,  // Slow SQL threshold
			LogLevel:      logger.Error, // Log level
			Colorful:      true,         // Disable color
		},
	)

	db, err := gorm.Open(iris.New(iris.Config{
		DSN: connectionString,
	}), &gorm.Config{
		Logger: newLogger,
	})
	if !useContainer {
		_ = db.Exec("DROP DATABASE TEST").Error
		_ = db.Exec("CREATE DATABASE TEST").Error
		_ = db.Exec("USE DATABASE TEST").Error
	}

	if err != nil {
		fmt.Println("storage err: ", err)
	}
	return db
}

func DropTestDB() error {
	if container != nil {
		container.Terminate(context.Background())
	}
	container = nil
	return nil
}

func AutoMigrate(db *gorm.DB) {
	db.AutoMigrate(
		&model.User{},
		&model.Follow{},
		&model.Article{},
		&model.Comment{},
		&model.Tag{},
	)
}

Using containerized IRIS is set under a cli flag and set in a handler_test.go file

var (
	useContainer bool
)

func TestMain(m *testing.M) {
	flag.BoolVar(&useContainer, "container", true, "Use container image.")
	flag.Parse()
	// setup()
	code := m.Run()
	// tearDown()
	os.Exit(code)
}

func setup() {
	d = db.TestDB(useContainer)
	db.AutoMigrate(d)
	us = store.NewUserStore(d)
	as = store.NewArticleStore(d)
	h = NewHandler(us, as)
	e = router.New()
	loadFixtures()
}

How It Works

  • When useContainer is true, the function launches a new IRIS container via testcontainers-iris-go.
    • It creates a clean environment with custom credentials (testuser / testpassword) and a namespace called TEST.
    • The connection string is retrieved automatically via container.MustConnectionString(ctx).
  • When running locally without containers, the code connects to a pre-existing IRIS instance and ensures the TEST database is recreated before tests run.
  • AutoMigrate() automatically creates all required tables using the models defined in the project (User, Article, Comment, etc.).

4. Run the Tests

Once the database configuration is in place, you can execute all tests using:

go test ./handler -v

flag -container or -container=0 can be added to swich the way of testing

This command will:

  • Build and run all Go tests in verbose mode.
  • Start a new IRIS container for each test (if enabled).
  • Automatically apply migrations and clean up after completion.

If everything is configured correctly, you’ll see log output similar to:

 
Tests result

5. Running the Application with Docker Compose

After confirming that tests pass successfully, the next step is to run the complete Fiber + GORM + IRIS application using Docker.
In this setup, the Go backend is built into a binary, copied into the IRIS container, and started automatically alongside IRIS itself.

This approach makes deployment extremely simple — you can spin up everything with one command.


Updated docker-compose.yml

The project’s modified docker-compose.yml now defines an iris service that handles both:

  • Running the InterSystems IRIS database.
  • Starting the Go Fiber application as part of the same container.

Here’s the key idea:

  • The Go app is built using a multistage Docker build.
  • The resulting binary is copied into the IRIS image.
  • A small init script is included to automatically start the Go app when IRIS launches.

This gives you a self-contained container — a single image that runs both IRIS and your Go web API in perfect sync.


Build and Start the Application

To build the IRIS image and launch the environment, simply run:

docker compose up -d iris --build

This will:

  1. Build your Go application.
  2. Create a new IRIS-based Docker image containing the app binary and initialization scripts.
  3. Start the container in detached mode (-d), with IRIS and the Go API running together.

💡 Note:
One of the beautiful aspects of Go is that you’re not limited to embedding your application inside the IRIS container.
Thanks to Go’s single-binary compilation, you can easily build a standalone Docker image for your application — one that connects to InterSystems IRIS over the network using the same connection string.

This approach has two big advantages:

  • The resulting image is much smaller, often under 30 MB.
  • It cleanly separates application logic from database infrastructure, making it ideal for microservices or cloud deployments.

In production, you can keep IRIS and your Go service in separate containers (or even separate hosts), connected securely through your network — combining IRIS’s reliability with Go’s portability.

6. End-to-End API Testing with Newman

Once your Go + IRIS application is up and running, it’s time to verify that the REST API behaves exactly as expected.
The project includes an additional layer of integration tests — using the Postman / Newman collection from the original RealWorld project.

This ensures that the backend fully complies with the RealWorld API specification and that all endpoints work correctly when backed by InterSystems IRIS.


Newman as a Service

To make testing seamless, the docker-compose.yml file defines an extra service named newman-checker.
This service runs the Newman CLI inside a container, executes the full RealWorld API test collection, and connects internally to the running Fiber + IRIS application.

Because both services run inside the same Docker network, the tests can access the backend directly without any extra configuration.


Run the API Tests

To execute the end-to-end tests, simply run:

docker compose run newman-checker

This will:

  1. Start the Newman container.
  2. Connect it to the running iris service.
  3. Execute the entire RealWorld API test suite against your Go + IRIS backend.

If everything is set up correctly, you should see a summary like:

 
Newman tests result

What This Confirms

Passing the Newman suite means your Go + Fiber + GORM + IRIS stack is fully compatible with the RealWorld API spec —
a great indicator that your backend logic, ORM integration, and database connectivity all work as expected.

It’s not just a demo anymore — it’s a production-grade, spec-compliant backend, powered by InterSystems IRIS.

7. Explore the API with Swagger UI

Once everything is up and running, you can finally explore the live REST API through a clean, interactive interface.
The project comes with a pre-generated Swagger UI, making it easy to inspect and test endpoints directly in your browser.

After starting the application, open:

👉 http://localhost:8585/swagger/index.html

You’ll see the full RealWorld API specification — all endpoints powered by your Go Fiber backend, connected through GORM to InterSystems IRIS.

From here, you can:

  • Register and log in users
  • Create, edit, and delete articles
  • Post comments
  • Follow or unfollow users

All the requests you send are processed in real time by IRIS, through the new Go driver and ORM integration.

What’s Next

You’ve now built and run a complete Go + Fiber + GORM + IRIS backend —
with automated tests, Swagger documentation, and containerized deployment.

From here, you can:

  • Extend the app with your own features.
  • Deploy IRIS and your Go app as separate services for scalability.
  • Experiment with advanced IRIS capabilities — globals, analytics, and interoperability.

This demo shows that InterSystems IRIS can be a first-class citizen in the modern Go ecosystem —
powerful, fast, and ready for cloud-native applications.


This project is participating in the contest, please vote here.

1 Comment
Discussão (1)2
Entre ou crie uma conta para continuar
Artigo
· Out. 7 5min de leitura

Présentation de testcontainers-iris-node: simplification des tests d'intégration IRIS dans Node.js

Aperçu Je suis ravi d'annoncer la sortie de testcontainers-iris-node, une bibliothèque Node.js qui facilite le lancement de conteneurs InterSystems IRIS temporaires pour l'intégration et les tests E2E. Ce projet vient naturellement compléter la gamme existante d'adaptateurs Testcontainers pour IRIS, notamment testcontainers-iris-python et testcontainers-iris-java.

Pourquoi testcontainers-iris-node? En tant que développeur Node.js travaillant avec InterSystems IRIS, j'ai souvent été confronté à des difficultés lors de la configuration d'environnements de test imitant la production. testcontainers-iris-node résout ce problème en exploitant le framework testcontainers-node pour créer des environnements IRIS isolés à la demande.

Ceci est particulièrement important pour:

  • Les tests d'intégration avec les bases de données IRIS
  • Les tests de pipelines de données ou de microservices
  • L'automatisation des environnements de test dans les pipelines CI

Fonctionnalités

  • Lancement d'IRIS dans des conteneurs Docker à l'aide de Testcontainers
  • Prise en charge des images et de la configuration Docker personnalisées
  • Stratégies d'attente pour s'assurer qu'IRIS est prêt avant le début des tests
  • Désinstallation de nettoyage entre les exécutions de tests

Discussão (0)2
Entre ou crie uma conta para continuar
Anúncio
· Out. 7

Resumen de aplicaciones de InterSystems Open Exchange, septiembre de 2025.

Hola y bienvenidos al resumen de Open Exchange de septiembre de 2025.
Estadísticas generales
✓ 13 nuevas aplicaciones
477 descargas
✓ 1.132 aplicaciones en total
✓ 42.871 descargas en total
✓ 3.343 desarrolladores registrados
Nuevas Aplicaciones
iris-execute-mcp
Por Joshua Brandt
SentinelIris
Por André Dienes Friedrich
FHIR Data Explorer with Hybrid Search and AI Summaries
Por Pietro Di Leo
Dashboard of database space
Por Robert Cemper
ToolQA
Por Andre Larsen Barbosa
IAM HA Deployments
Por Ariel Glikman
iris-recordmap-fordummies
Por Kurro Lopez
MessageLogViz
Por Ashok Kumar T
Snapshot of free disk space
Por Robert Cemper
RAGBookRecommender
Por Gabriel Ing
TaskScheduler
Por Ashok Kumar T
A Configurable Template for Automated Splitting of HL7 Repeating Segments
Por Sanjib Pandey
UNICAS Implementation
Por Luis Angel Pérez Ramos
Nuevos lanzamientos
csvgen de Evgeny Shvarov
v1.7.1
Se añadió el método Gen() para habilitar calificadores JSON; por ejemplo: para añadir, llamadlo de la siguiente manera:
set status=##class(community.csvgen).Gen(fname,,.pclass,.prowtype,{"append":1},.recordCount)
o configurad los calificadores de antemano, como:
set qualifiers={"verbose":1,"PrimaryKey":"name"}
set status=##class(community.csvgen).Gen(fname,,.pclass,.prowtype,qualifiers,.recordCount)
snapshot-to-JSON de Robert Cemper
v1.10.0
  • ampliado el README con un ejemplo de la demo
  • ampliado el README con una guía de instalación estándar
  • simplificada la compilación
  • añadida ZPrety para la demo
InterSystems Testing Manager for VS Code de John Murray
v2.0.4
  • Corregida la subcarpeta de Server Tests que se quedaba cargando indefinidamente al expandirse.
  • Modo del lado del servidor: excluir las clases TestCase mapeadas.
iris-dataset-countries de Evgeny Shvarov
v1.1.4
Más países, variaciones de nombres y correcciones.
MDX2JSON de Eduard Lebedyuk
v3.2.48
Rollback
Embedded Git de Pravin Barton
v2.13.1

[2.13.1] - 2025-09-16

Correcciones

  • Corregido el problema de “Importar todo” que desplegaba cambios en archivos de una aplicación CSP (#828)
  • Corregido el fallo al hacer pull cuando los elementos eliminados no tenían nombre interno ni externo (#848)
  • Corregido un error por el cual las páginas de control de código fuente no se mostraban después de la instalación en IRIS 2025.1 (#852)
Test Coverage Tool por Timothy Leavitt
v4.0.7

[4.0.7] - 2025-09-23

Correcciones

  • #66: Ya no se producen errores cuando un método con[ Language = python ]tiene un nombre que comienza con “%”.
  • Los archivos coverage.list con finales de línea al estilo de Windows ahora se analizan correctamente en contenedores.
Más descargadas
MDX2JSON
Por Eduard Lebedyuk
zpm-registry
Por Evgeny Shvarov
WebTerminal
Por Nikita Savchenko
DeepSeeWeb
Por Anton Gnibeda
ObjectScript-Math
Por Peter Steiwer
Intersystems-Monitoring
Por Teunis Stolker
iris-web-swagger-ui
Por Semion Makarov
yaml-utils
Por Benjamin De Boe
Test Coverage Tool
Por Timothy Leavitt
passwordless
Por Sergey Mikhailenko
, 2025Month at a GlanceInterSystems Open Exchange
Discussão (0)1
Entre ou crie uma conta para continuar
Artigo
· Out. 7 6min de leitura

La espera ha terminado: damos la bienvenida al soporte de GoLang para InterSystems IRIS

Introducción

La plataforma de datos InterSystems IRIS ha sido conocida durante mucho tiempo por su rendimiento, interoperabilidad y flexibilidad entre distintos lenguajes de programación. Durante años, los desarrolladores pudieron usar IRIS con Python, Java, JavaScript y .NET, pero los desarrolladores de Go (o Golang) tuvieron que esperar.

Golang Logo

Esa espera finalmente ha terminado.

El nuevo controlador go-irisnative incorpora soporte para GoLang en InterSystems IRIS, implementando la API estándar database/sql. Esto significa que los desarrolladores de Go ahora pueden utilizar herramientas de base de datos conocidas, agrupación de conexiones e interfaces de consulta para crear aplicaciones impulsadas por IRIS.


Por qué es importante el soporte para GoLang

GoLang es un lenguaje diseñado para la simplicidad, la concurrencia y el rendimiento, ideal para arquitecturas nativas en la nube y basadas en microservicios. Impulsa algunos de los sistemas más escalables del mundo, como Kubernetes, Docker y Terraform.

Integrar IRIS en el ecosistema de Go permite:

  • Servicios ligeros y de alto rendimiento utilizando IRIS como backend.
  • Concurrencia nativa para la ejecución paralela de consultas o el procesamiento en segundo plano.
  • Integración fluida con sistemas distribuidos y en contenedores.
  • Acceso a bases de datos de forma idiomática mediante la interfaz database/sql de Go.

Esta integración convierte a IRIS en la opción perfecta para aplicaciones modernas y preparadas para la nube desarrolladas en Go.


Cómo empezar

1. Instalación

go get github.com/caretdev/go-irisnative

2. Conectar a IRIS

Así es como se realiza la conexión utilizando la API estándar database/sql:

import (
    "database/sql"
    "fmt"
    "log"
    _ "github.com/caretdev/go-irisnative"
)

func main() {
    db, err := sql.Open("iris", "iris://_SYSTEM:SYS@localhost:1972/USER")
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()

    // Simple ping to test connection
    if err := db.Ping(); err != nil {
        log.Fatal("Failed to connect:", err)
    }

    fmt.Println("Connected to InterSystems IRIS!")
}

3. Creación de una tabla

Vamos a crear una tabla de demostración sencilla:

_, err = db.Exec(`CREATE TABLE IF NOT EXISTS demo (
    id INT PRIMARY KEY,
    name VARCHAR(50)
)`)
if err != nil {
    log.Fatal(err)
}
fmt.Println("Table created.")

4. Inserción de datos

Por el momento, no se admiten inserciones de varias filas; se debe insertar una fila por cada llamada:

_, err = db.Exec(`INSERT INTO demo (id, name) VALUES (?, ?)`, 1, "Alice")
if err != nil {
    log.Fatal(err)
}

_, err = db.Exec(`INSERT INTO demo (id, name) VALUES (?, ?)`, 2, "Bob")
if err != nil {
    log.Fatal(err)
}

fmt.Println("Data inserted.")

5. Consulta de datos

La consulta es sencilla utilizando la interfaz database/sql

rows, err := db.Query(`SELECT id, name FROM demo`)
if err != nil {
    log.Fatal(err)
}
defer rows.Close()

for rows.Next() {
    var id int
    var name string
    if err := rows.Scan(&id, &name); err != nil {
        log.Fatal(err)
    }
    fmt.Printf("ID: %d, Name: %s\n", id, name)
}

That’s all you need to perform basic SQL operations from Go.


Cómo funciona

Bajo el capó, el controlador go-irisnativeutiliza la API nativa de IRIS para una comunicación eficiente y de bajo nivel con la base de datos. El controlador implementa las interfaces estándar database/sql/driver de Go, lo que lo hace compatible con herramientas existentes de Go como:

  • sqlx
  • gorm (con un dialecto personalizado)
  • Herramientas estándar de migración en Go

Esto ofrece a los desarrolladores una API familiar con la potencia y el rendimiento del acceso nativo a IRIS.


Ejemplos de casos de uso

  • Microservicios — servicios ligeros en Go conectados directamente a IRIS.
  • APIs de datos — exposición de endpoints REST o gRPC respaldados por IRIS.
  • Herramientas de integración — conexión de los datos de IRIS con otros sistemas en flujos desarrollados en Go.
  • Aplicaciones IRIS nativas en la nube — despliegue de aplicaciones en Go respaldadas por IRIS en Kubernetes o Docker.

Pruebas con Testcontainers

Si deseas ejecutar pruebas automatizadas sin tener que gestionar una instancia activa de IRIS, puedes usar testcontainers-iris-go.
Este lanza un contenedor temporal de IRIS para realizar pruebas de integración.

Ejemplo de configuración de prueba:

import (
    "context"
    "database/sql"
    "flag"
    "log"
    "os"
    "testing"
    iriscontainer "github.com/caretdev/testcontainers-iris-go"
    "github.com/stretchr/testify/require"
    "github.com/testcontainers/testcontainers-go"
)

var connectionString string = "iris://_SYSTEM:SYS@localhost:1972/USER"
var container *iriscontainer.IRISContainer = nil
func TestMain(m *testing.M) {
    var (
        useContainer   bool
        containerImage string
    )
    flag.BoolVar(&useContainer, "container", true, "Use container image.")
    flag.StringVar(&containerImage, "container-image", "", "Container image.")
    flag.Parse()
    var err error
    ctx := context.Background()
    if useContainer || containerImage != "" {
        options := []testcontainers.ContainerCustomizer{
            iriscontainer.WithNamespace("TEST"),
            iriscontainer.WithUsername("testuser"),
            iriscontainer.WithPassword("testpassword"),
        }
        if containerImage != "" {
            container, err = iriscontainer.Run(ctx, containerImage, options...)
        } else {
            // or use default docker image
            container, err = iriscontainer.RunContainer(ctx, options...)
        }
        if err != nil {
            log.Println("Failed to start container:", err)
            os.Exit(1)
        }
        defer container.Terminate(ctx)
        connectionString = container.MustConnectionString(ctx)
        log.Println("Container started successfully", connectionString)
    }

    var exitCode int = 0
    exitCode = m.Run()

    if container != nil {
        container.Terminate(ctx)
    }
    os.Exit(exitCode)
}

func openDbWrapper[T require.TestingT](t T, dsn string) *sql.DB {
    db, err := sql.Open(`intersystems`, dsn)
    require.NoError(t, err)
    require.NoError(t, db.Ping())
    return db
}

func closeDbWrapper[T require.TestingT](t T, db *sql.DB) {
    if db == nil {
        return
    }
    require.NoError(t, db.Close())
}

func TestConnect(t *testing.T) {
    db := openDbWrapper(t, connectionString)
    defer closeDbWrapper(t, db)

    var (
        namespace string
        username  string
    )
    res := db.QueryRow(`SELECT $namespace, $username`)
    require.NoError(t, res.Scan(&namespace, &username))
    require.Equal(t, "TEST", namespace)
    require.Equal(t, "testuser", username)
}

Esto es ideal para pipelines de CI/CD o pruebas unitarias, garantizando que tu aplicación en Go funcione perfectamente con IRIS de forma aislada.


Conclusión

El soporte de GoLang para InterSystems IRIS ya está aquí, y marca un antes y un después.
Con go-irisnative, ahora puedes crear aplicaciones escalables, concurrentes y nativas en la nube que aprovechen directamente la potencia de IRIS.

Tanto si estás desarrollando microservicios, APIs o herramientas de integración, Go te ofrece simplicidad y rendimiento, mientras que IRIS te brinda fiabilidad y amplias capacidades de gestión de datos.

👉 Probadlo:

Discussão (0)1
Entre ou crie uma conta para continuar