Sample API server to receive JSON in Golang

Sample code

main.go


package main

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

//Declare structure
type User struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

func main() {
	// POST
    http.HandleFunc("/post", func(w http.ResponseWriter, r *http.Request) {
        var user User
        json.NewDecoder(r.Body).Decode(&user)

        fmt.Fprintf(w, "%s is %d years old!", user.Name, user.Age)
    })

    // GET
    http.HandleFunc("/get", func(w http.ResponseWriter, r *http.Request) {
        yuta := User{
            Name:  "yuta",
            Age:       666,
        }

        json.NewEncoder(w).Encode(yuta)
    })

    http.ListenAndServe(":8080", nil)
}


Post and Get

yuta:~ $ curl -s http://localhost:8080/get
{"name":"yuta","age":666}
yuta:~ $ 
yuta:~ $ 
yuta:~ $ curl -s -XPOST -d'{"name":"tadokoro","age":24}' http://localhost:8080/post
tadokoro is 24 years old!yuta:~ $ 
yuta:~ $ 
yuta:~ $ 

Recommended Posts

Sample API server to receive JSON in Golang
Procedure from HTML to JSON Ajax communication of API server
Introduction to Socket API Learned in C Part 3 TCP Server / Client # 1
Introduction to Socket API Learned in C Language Part 1 Server Edition
Hit the New Relic API in Python to get the server status
Introduction to Socket API Learned in C Part 4 UDP Server / Client # 1
Sample script to trap signals in Python
Convert array (struct) to json with golang
Control files to build in Golang project
I'm addicted to the difference in how Flask and Django receive JSON data
Log in to the remote server with SSH
How to receive command line arguments in Python
How to create a JSON file in Python
POST JSON in Python and receive it in PHP
How to create a Rest Api in Django
Use pygogo to get the log in json.
Sample to put Python Kivy in one file
Parse a JSON string written to a file in Python
I want to randomly sample a file in Python
How to make an interactive CLI tool in Golang
Try to delete tweets in bulk using Twitter API
Convert callback-style asynchronous API to async / await in Python
Convert / return class object to JSON format in Python
Stumble when converting bidirectional list to JSON in Go
How to handle JSON in Ruby, Python, JavaScript, PHP
API implementation to toggle values in two ways (go)