From Express to Go: what changes in the backend

A practical comparison of error handling, types, concurrency, and database work

I work with both Express and Go/Gin. The routes can look familiar, but Go makes you decide explicitly what happens when a call returns an error.

The handler below is an illustrative example, not a production excerpt. After that, I’ll look at types, goroutines, and transaction boundaries.

Make failure part of the contract

In an Express application, asynchronous failures often travel through rejected promises and error middleware. In Go, a function commonly returns both a result and an error. The caller decides whether to recover, add context, translate the failure, or return it.

Check the error before using the result unless the function explicitly documents a usable partial result. An error return is not automatically sent to Gin or converted into an HTTP response.

This complete handler example uses a small dependency interface. Its implementation could query a database, but no database behavior is assumed here:

package api

import (
	"context"
	"errors"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

var ErrNotFound = errors.New("user not found")

type User struct {
	ID   int64  `json:"id"`
	Name string `json:"name"`
}

type UserReader interface {
	FindUser(ctx context.Context, id int64) (User, error)
}

func GetUser(users UserReader) gin.HandlerFunc {
	return func(c *gin.Context) {
		id, err := strconv.ParseInt(c.Param("id"), 10, 64)
		if err != nil || id <= 0 {
			c.JSON(http.StatusBadRequest, gin.H{"error": "invalid user id"})
			return
		}

		user, err := users.FindUser(c.Request.Context(), id)
		switch {
		case errors.Is(err, ErrNotFound):
			c.JSON(http.StatusNotFound, gin.H{"error": "user not found"})
		case err != nil:
			c.JSON(http.StatusInternalServerError, gin.H{"error": "request failed"})
		default:
			c.JSON(http.StatusOK, user)
		}
	}
}

The dependency contract should specify that missing users return ErrNotFound, possibly wrapped. errors.Is handles wrapping when the implementation preserves the original error with %w. Internal database details should be logged through the application's logging policy, not returned to clients.

Do not replace normal error handling with panic. A missing record or unavailable dependency is an expected operational possibility, not a reason to unwind the program unexpectedly.

Use types without confusing them with validation

Go catches many structural mistakes before execution: passing a string where an integer is required, calling an absent method, or assigning an incompatible result. Interface satisfaction is implicit, so the handler's dependency does not need an explicit declaration that it implements UserReader.

Types cannot establish that an ID is positive, a caller owns a record, or an email address satisfies product rules. Successful JSON decoding also does not prove that every required field was present. A missing numeric field can become zero, indistinguishable from an explicit zero unless the request representation preserves that distinction.

Use separate request types when transport fields differ from domain data. Use pointers or another explicit representation when absence matters. Validate at the boundary, then enforce business rules where the operation lives. Static typing reduces one category of mistakes; it does not replace runtime checks, authorization, or tests.

Add layers when responsibilities actually differ

An Express controller, service, and repository can map to Go handlers, application operations, and persistence code. They do not need to become three packages for every endpoint.

A handler owns HTTP parsing and response mapping. A service becomes useful when an operation coordinates rules, authorization decisions, or several dependencies. A repository becomes useful when persistence details would otherwise leak into those decisions.

Keep interfaces small and place them near the code that consumes them. The example needs only one read operation, not a universal repository interface. A thin endpoint may need only a handler and query function. Add separation to protect a real boundary, not to reproduce a directory diagram.

Know when concurrent work ends

A JavaScript promise represents eventual completion; creating one does not inherently create a thread. Node.js coordinates asynchronous I/O through its event loop and supporting runtime facilities. CPU-heavy JavaScript still needs deliberate isolation to avoid blocking that loop.

A goroutine is a concurrently executing function scheduled by the Go runtime onto operating-system threads. Goroutines can run in parallel, but neither parallelism nor a speedup follows automatically from adding go.

Every spawned task needs answers to four questions: who waits for it, who cancels it, where its errors go, and what limits its resource use? A goroutine per unbounded input can overwhelm a database connection pool just as easily as unbounded Promise.all work.

Propagate the request context into database and network operations that support it. Cancellation is cooperative: passing a context does not forcibly stop arbitrary computation. Do not keep using Gin's request context from detached work after the request finishes. Durable background work needs its own lifecycle and usually a queue or job system, not an unobserved goroutine.

Own database access and transaction boundaries

With Go's database/sql, *sql.DB is a concurrency-safe pool, not one connection per request. Create and configure it at application startup, share it, and close it during shutdown. With row iteration, close the rows and check rows.Err() afterward; iteration can fail after a successful query call.

Keep parameter values separate from SQL text using the placeholders your driver supports. String formatting is not a substitute for query parameters.

A transaction belongs to the operation that requires atomicity. Begin it with BeginTx, arrange a deferred rollback for early returns, execute every participating query through the resulting *sql.Tx, and check the error from Commit. Calling the pool directly halfway through can put that query outside the transaction.

Atomicity alone does not prevent every concurrency anomaly. If a decision depends on a value read earlier, consider an atomic conditional update, suitable locking, or an isolation level appropriate to the database. Keep transactions short and avoid holding them open during slow external API calls. A committed database change and a remote HTTP request are not automatically one atomic operation.

Do not rewrite a working backend to practice syntax

Go may be a good fit for a service with clear operational or maintenance requirements. That does not make an Express rewrite the default next step. A rewrite also replaces known behavior, deployment assumptions, and failure handling, not just source files.

First identify a concrete constraint. Measure it, consider improving the existing implementation, and choose a bounded component if migration is justified. Preserve API contracts and test failure behavior as carefully as successful responses.

Don’t aim to write JavaScript in Go. Aim for a backend the next developer can follow and maintain.

Have a question or a different take?