Go

JSON API Endpoint

admin by @admin ADMIN
5d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Decode an incoming JSON body into a typed struct, do work, encode a JSON response. The whole roundtrip is ~20 lines of standard library.
Go
Raw
package main

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

type CreateUserRequest struct {
    Name  string `json:"name"`
    Email string `json:"email"`
}

type User struct {
    ID    int    `json:"id"`
    Name  string `json:"name"`
    Email string `json:"email"`
}

func createUser(w http.ResponseWriter, r *http.Request) {
    if r.Method != http.MethodPost {
        http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
        return
    }
    var req CreateUserRequest
    if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
        http.Error(w, "bad json: "+err.Error(), http.StatusBadRequest)
        return
    }
    user := User{ID: 42, Name: req.Name, Email: req.Email}

    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusCreated)
    json.NewEncoder(w).Encode(user)
}

func main() {
    http.HandleFunc("/users", createUser)
    log.Fatal(http.ListenAndServe(":8080", nil))
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.