1. Home
  2. /
  3. Martini
  4. /
  5. Simple REST API

Simple REST API - Martini Typing CST Test

Loading…

Simple REST API — Martini Code

Demonstrates a simple Martini application with routes for listing and creating Todo items.

package main

import (
	"github.com/go-martini/martini"
	"net/http"
	"encoding/json"
)

type Todo struct {
	ID        int    `json:"id"`
	Title     string `json:"title"`
	Completed bool   `json:"completed"`
}

var todos []Todo

func main() {
	m := martini.Classic()

	m.Get("/todos", func(res http.ResponseWriter) {
		json.NewEncoder(res).Encode(todos)
	})

	m.Post("/todos", func(req *http.Request, res http.ResponseWriter) {
		var todo Todo
		json.NewDecoder(req.Body).Decode(&todo)
		todos = append(todos, todo)
		res.WriteHeader(http.StatusCreated)
		json.NewEncoder(res).Encode(todo)
	})

	m.Run()
}

Martini Language Guide

Martini is a lightweight web framework for Go, designed for rapid development with simplicity and minimal boilerplate.

Primary Use Cases

  • ▸RESTful APIs and JSON services
  • ▸Small web applications and prototypes
  • ▸Middleware-driven microservices
  • ▸Rapid prototyping of Go applications
  • ▸Educational and learning projects in Go

Notable Features

  • ▸Lightweight and minimalistic
  • ▸Middleware-driven design
  • ▸Routing with parameters and patterns
  • ▸Built-in dependency injection
  • ▸Support for templates and static files

Origin & Creator

Created by Codegangsta (now known as Unrolled) in 2011, originally popularized in the Go community.

Industrial Note

Martini is favored for small to medium Go web services, APIs, and microservices where simplicity and rapid development outweigh large-scale ecosystem needs.

Practice Other Languages

CReactPythonC++RustTypeScriptKotlinPHPJavaC#RubyMqlCqlN1qlCypher