Easy to create API server using go-json-rest module

Repository

https://github.com/ant0ine/go-json-rest

Program to display Hello world

main.go


package main

import (
        "github.com/ant0ine/go-json-rest/rest"
        "log"
        "net/http"
)

func main() {
        api := rest.NewApi()
        api.Use(rest.DefaultDevStack...)
        api.SetApp(rest.AppSimple(func(w rest.ResponseWriter, r *rest.Request) {
                w.WriteJson(map[string]string{"Body": "Hello World!"})
        }))
        log.Fatal(http.ListenAndServe(":8080", api.MakeHandler()))
}
yuta:~ $ curl -i http://127.0.0.1:8080/
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
X-Powered-By: go-json-rest
Date: Sun, 01 Nov 2020 00:54:41 GMT
Content-Length: 28

{
  "Body": "Hello World!"
}yuta:~ $ 

POST,GET,DELETE

main.go


package main

import (
        "github.com/ant0ine/go-json-rest/rest"
        "log"
        "net/http"
        "sync"
)

func main() {
        api := rest.NewApi()
        api.Use(rest.DefaultDevStack...)
        router, err := rest.MakeRouter(
                rest.Get("/countries", GetAllCountries),
                rest.Post("/countries", PostCountry),
                rest.Get("/countries/:code", GetCountry),
                rest.Delete("/countries/:code", DeleteCountry),
        )
        if err != nil {
                log.Fatal(err)
        }
        api.SetApp(router)
        log.Fatal(http.ListenAndServe(":8080", api.MakeHandler()))
}

type Country struct {
        Code string
        Name string
}

var store = map[string]*Country{}

var lock = sync.RWMutex{}

func GetCountry(w rest.ResponseWriter, r *rest.Request) {
        code := r.PathParam("code")

        lock.RLock()
        var country *Country
        if store[code] != nil {
                country = &Country{}
                *country = *store[code]
        }
        lock.RUnlock()

        if country == nil {
                rest.NotFound(w, r)
                return
        }
        w.WriteJson(country)
}

func GetAllCountries(w rest.ResponseWriter, r *rest.Request) {
        lock.RLock()
        countries := make([]Country, len(store))
        i := 0
        for _, country := range store {
                countries[i] = *country
                i++
        }
        lock.RUnlock()
        w.WriteJson(&countries)
}

func PostCountry(w rest.ResponseWriter, r *rest.Request) {
        country := Country{}
        err := r.DecodeJsonPayload(&country)
        if err != nil {
                rest.Error(w, err.Error(), http.StatusInternalServerError)
                return
        }
        if country.Code == "" {
                rest.Error(w, "country code required", 400)
                return
        }
        if country.Name == "" {
                rest.Error(w, "country name required", 400)
                return
        }
        lock.Lock()
        store[country.Code] = &country
        lock.Unlock()
        w.WriteJson(&country)
}

func DeleteCountry(w rest.ResponseWriter, r *rest.Request) {
        code := r.PathParam("code")
        lock.Lock()
        delete(store, code)
        lock.Unlock()
        w.WriteHeader(http.StatusOK)
}

POST

yuta:~ $ curl -i -H 'Content-Type: application/json' \
>     -d '{"Code":"FR","Name":"France"}' http://127.0.0.1:8080/countries
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
X-Powered-By: go-json-rest
Date: Sun, 01 Nov 2020 00:59:38 GMT
Content-Length: 38

{
  "Code": "FR",
  "Name": "France"
}yuta:~ $ 

GET

yuta:~ $ curl -i http://127.0.0.1:8080/countries/FR
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
X-Powered-By: go-json-rest
Date: Sun, 01 Nov 2020 01:01:02 GMT
Content-Length: 38

{
  "Code": "FR",
  "Name": "France"
}yuta:~ $ 

DELETE

yuta:~ $ curl -i -X DELETE http://127.0.0.1:8080/countries/FR
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
X-Powered-By: go-json-rest
Date: Sun, 01 Nov 2020 01:01:35 GMT
Content-Length: 0

yuta:~ $ curl -i http://127.0.0.1:8080/countries/FR
HTTP/1.1 404 Not Found
Content-Type: application/json; charset=utf-8
X-Powered-By: go-json-rest
Date: Sun, 01 Nov 2020 01:01:41 GMT
Content-Length: 35

{
  "Error": "Resource not found"
}yuta:~ $ 
yuta:~ $ ^C

Recommended Posts

Easy to create API server using go-json-rest module
Try to create an HTTP server using Node.js
An easy way to create an import module with jupyter
Create a pseudo REST API server using GitHub Pages
I tried to create Quip API
Create API using hug with mod_wsgi
Create a CRUD API using FastAPI
[Python] Create API to send Gmail
Create Python module [CarSensor API support module csapi]
Create a graph using the Sympy module
Create an application using the Spotify API
How to display Map using Google Map API (Android)
Procedure to use TeamGant's WEB API (using python)
Let's create a REST API using SpringBoot + MongoDB
Easy way to plot HR diagram using astroquery
Write a TCP server using the SocketServer module
How to get article data using Qiita API
Sample API server to receive JSON in Golang
How to create a Rest Api in Django
How to uninstall a module installed using setup.py
Prepare a pseudo API server using GitHub Actions
Create an API server quickly with Python + Falcon
How to create random numbers with NumPy's random module
I tried to operate from Postman using Cisco Guest Shell as an API server
[Rails] How to get location information using Geolocation API
Pre-processing to build seq2seq model using keras Functional API
Fatal error in launcher: Unable to create process using'"'
Push notifications from Python to Android using Google's API
Easy way to scrape with python using Google Colab
Try to make RESTful API with MVC using Flask 1.0.2
Fatal error in launcher: Unable to create process using'"'
Write data to KINTONE using the Python requests module
Try to delete tweets in bulk using Twitter API
Post to your account using the API on Twitter
Learning neural networks using Chainer-Creating a Web API server
How to create a simple TCP server / client script
How to analyze with Google Colaboratory using Kaggle API
Easy usage memo of OpenStack Swift API using swiftclient
A script that makes it easy to create rich menus with the LINE Messaging API