← Project templates

WEB AND APIS · IN THE APP NOW

Gin REST API

A small books API written against Gin's core API. It builds offline on iPhone and iPad, and the same code compiles unchanged against upstream Gin v1.12 on a server.

Offline: bundled Gin-compatible subset

Open it in the browser Playground →

What it is

On the device the project uses GopherForge's bundled Gin-compatible subset, vendored into the project. It covers the core routing and JSON API: GET, POST, PUT, PATCH and DELETE routes, Param, Query, ShouldBindJSON, JSON and ServeHTTP. Route groups and middleware chains are not part of it, so the template uses only what the subset and upstream Gin share.

The app's sandbox has no sockets, so main does not call router.Run. It replays the requests a client would send through router.ServeHTTP with net/http/httptest and prints each status and body. books_test.go does the same with a table of cases.

Every template's Go program was compiled for GOOS=wasip1 GOARCH=wasm with Go 1.27, then run, vetted and tested before it was added to the app.

Files

text
gin-api/
├── vendor/
│   ├── github.com/gin-gonic/gin/
│   │   ├── README.md
│   │   ├── gin.go
│   │   └── offline.go
│   └── modules.txt
├── books.go
├── books_test.go
├── go.mod
└── main.go

The code

books.go

go
func newRouter(lib *library) *gin.Engine {
	router := gin.Default()
	router.GET("/health", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{"status": "ok"})
	})
	router.GET("/books", lib.list)
	router.GET("/books/:id", lib.get)
	router.POST("/books", lib.create)
	router.DELETE("/books/:id", lib.remove)
	return router
}

books.go

go
func (lib *library) create(c *gin.Context) {
	var book Book
	if err := c.ShouldBindJSON(&book); err != nil || book.Title == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "a book needs a title"})
		return
	}
	lib.mu.Lock()
	defer lib.mu.Unlock()
	book.ID = lib.next
	lib.next++
	lib.books[book.ID] = book
	c.JSON(http.StatusCreated, book)
}

books_test.go

go
package main

import (
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
)

func TestBooks(t *testing.T) {
	router := newRouter(newLibrary())
	cases := []struct {
		name, method, path, body string
		want                     int
	}{
		{"create", "POST", "/books", `{"title":"Go in Action"}`, http.StatusCreated},
		{"missing title", "POST", "/books", `{}`, http.StatusBadRequest},
		{"read", "GET", "/books/1", "", http.StatusOK},
		{"not a number", "GET", "/books/one", "", http.StatusBadRequest},
		{"unknown", "GET", "/books/42", "", http.StatusNotFound},
	}
	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			recorder := httptest.NewRecorder()
			router.ServeHTTP(recorder, httptest.NewRequest(tc.method, tc.path, strings.NewReader(tc.body)))
			if recorder.Code != tc.want {
				t.Fatalf("%s %s = %d, want %d: %s", tc.method, tc.path, recorder.Code, tc.want, recorder.Body)
			}
		})
	}
}

What you learn

  • Register routes with router.GET, POST and DELETE and read the :id segment with c.Param.
  • Bind a JSON body with c.ShouldBindJSON and answer 400 when it is missing or invalid.
  • Reply with c.JSON, using a struct or a gin.H map, and the status code that fits.
  • Guard an in-memory store with sync.Mutex so it can be replaced by a database without touching the handlers.
  • Test the whole router in-process with a table-driven httptest test.

Run it on a server

Remove the vendored subset and require upstream Gin. Then replace the request loop in main with router.Run(":8080"), import log, and drop the imports main no longer uses. The handlers and the test stay as they are.

go
func main() {
	router := newRouter(newLibrary())
	log.Fatal(router.Run(":8080"))
}
bash
rm -rf vendor
go mod edit -droprequire github.com/gin-gonic/gin
go get github.com/gin-gonic/gin@v1.12.0
go mod tidy
go test ./...
go run .
curl localhost:8080/books

Related: Gin course · Table-driven API tests through the real router · Go services