Categorygithub.com/jimdn/restful/v2
modulepackage
2.0.9
Repository: https://github.com/jimdn/restful.git
Documentation: pkg.go.dev

# README

jimdn/restful

A package based on Golang and MongoDB for quickly building HTTP RESTful services with JSON.

MIT License Go Report Card

Required

  • go 1.13+
  • mongodb v3.4.x v3.6.x
  • elasticsearch v6.8.x v7.x.x (if enable searching)

Installation

Use go get.

go get github.com/jimdn/restful/v2

Then import the package into your own code.

import "github.com/jimdn/restful/v2"

Feature Overview

  • Define the structure of the data resource (including json and bson tags), then you can implement the CURD service of HTTP+JSON. The protocol is as follows:
HTTP MethodPathURL ParamsHTTP BodyExplain
POST/{biz}-data to be insertedinsert data
PUT/{biz}/{id}-data to be upsertedinsert or update(overwrite) data by id
PATCH/{biz}/{id}seqdata to be updatedupdate data by id
DELETE/{biz}/{id}--delete data by id
GET/{biz}/{id}--get data by id
GET/{biz}page
size
filter
range
in
nin
all
search
order
select
-get list of data:
page=1
size=10
filter={"star":5, "city":"shenzhen"}
range={"age":{"gt":20, "lt":40}}
in={"color":["blue", "red"]}
nin={"color":["blue", "red"]}
all={"color":["blue", "red"]}
search=hello
order=["+age", "-time"]
select=["id", "name", "age"]
  • When defining a data resource structure, the supported data types include:

    common types: bool int32 uint32 int64 uint64 float32 float64 string struct
    array types: []bool []int32 []uint32 []int64 []uint64 []float32 []float64 []string []struct
    map types: map[string]bool map[string]int32 map[string]uint32 map[string]int64 map[string]uint64 map[string]float32 map[string]float64 map[string]string  map[string]struct
    
  • Support field level CreateOnly or ReadOnly:

    • CreateOnly: only allows creation, does not allow subsequent modification of the field
    • ReadOnly: only allows reading, does not allow creation and modification, is suitable for importing data from other systems to the database, and then providing data reading services.
  • With the field check function, the incoming data field type is wrong or does not exist, it will return a failure and prompt specific error information.

  • Support custom data ID or automatically create ID (UUIDv4), pay attention to the writing of tags:

      type Foo struct {
          Id  *string  `json:"id,omitempty" bson:"_id,omitempty"`
          ...
      }
    
  • Support tracking data birth time and modify time, two additional fields required:

    • btime: birth time, record the timestamp when data created
    • mtime: modify time, record the timestamp the last modification of data
  • Support anti-concurrent writing, the seq field required:

    • seq: will be updated each time the data is modified, the update (PATCH) request needs to bring the data original seq to prevent concurrent writing from causing data confusion.
  • Support custom database name and table name, with URL params:

    • db: database name, default is restful
    • table: table name, default is {Biz}

    e.g.: /{Biz}?db=dbName&table=tableName

How to use

See examples. We take the Student of simple.go as an example:

Insert resource (with or without id)

Request:

POST /student HTTP/1.1
Content-Type: application/json; charset=utf-8
Content-Length: 226

{
    "id": "student-id-001",
    "name": "jimmydeng",
    ...
}

Response:

HTTP/1.1 200 OK
Date: Mon, 22 Apr 2019 06:46:23 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 91

{
    "code": 0,
    "msg": "post ok",
    "data": {
        "id": "student-id-001"
    }
}

Upsert resource by id

Request:

PUT /student/student-id-001 HTTP/1.1
Content-Type: application/json; charset=utf-8
Content-Length: 226

{
    "id": "student-id-001",
    "name": "jimmydeng",
    ...
}

Response:

HTTP/1.1 200 OK
Date: Mon, 22 Apr 2019 06:46:23 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 90

{
    "code": 0,
    "msg": "put ok",
    "data": {
        "id": "student-id-001"
    }
}

Update resource by id

Request:

PATCH /student/student-id-001?seq=1 HTTP/1.1
Content-Type: application/json; charset=utf-8
Content-Length: 226

{
    "id": "student-id-001",
    "name": "jimmydeng02",
    ...
}

Response:

HTTP/1.1 200 OK
Date: Mon, 22 Apr 2019 06:46:23 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 30

{
    "code": 0,
    "msg": "patch ok",
    "data": {
        "id": "student-id-001"
    }
}

Delete resource by id

Request:

DELETE /student/student-id-001 HTTP/1.1

Response:

HTTP/1.1 200 OK
Date: Mon, 22 Apr 2019 06:46:23 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 30

{
    "code": 0,
    "msg": "delete ok",
    "data": {
        "id": "student-id-001"
    }
}

Get resource by id

Request:

GET /student/student-id-001 HTTP/1.1

Response:

HTTP/1.1 200 OK
Date: Mon, 22 Apr 2019 06:46:23 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 537

{
    "code": 0,
    "msg": "get ok",
    "data": {
        "id": "student-id-001"
        "name": "jimmydeng",
        ...
    }
}

Get resources

Request:

GET /student?page=1&size=10 HTTP/1.1

Response:

HTTP/1.1 200 OK
Date: Mon, 22 Apr 2019 06:46:23 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 797

{
    "code": 0,
    "msg": "get page ok",
    "data": {
        "total": 238,
        "hits": [
            {
                "id": "student-id-001",
                "name": "jimmydeng",
                ...
            },
            {
                "id": "student-id-002",
                "name": "tonywho",
                ...
            }
            ...
        ]
    }
}

# Packages

No description provided by the author

# Functions

BuildFieldSet is a function to parsing the DataStruct.
CheckBool check v type if v is BOOL, return v if v is not BOOL, return nil.
CheckFloat check value type if value is any type represent FLOAT, return FLOAT64 value if value is not any type represent FLOAT, return nil.
CheckInt check value type if value is any type represent INT, return INT64 value if value is not any type represent INT, return nil.
CheckObject check value type if value is OBJECT, return its value if value is not OBJECT, return nil.
CheckString check value type if value is any type represent STRING, return STRING value if value is not any type represent STRING, return nil.
CheckUint check value type if value is any type represent UINT, return UINT64 value if value is not any type represent UINT, return nil.
EmptyValue get the default value of kind.
GenUniqueID is an function to gen a unique id with STRING type support objectid or uuid.
GetString check s type if s is String, return its value if s is not STRING, return empty string.
GetStringD check s type if s is String, return its value if s is not STRING, return default d.
Init is a function to init restful service.
IsEmpty check value is nin or default value of its kind.
IsEmptyArray check whether value is empty if value is nil or empty array, return true.
IsEmptyBool check whether value is empty if value is nil or default value of bool, return true.
IsEmptyNumber check whether value is empty if value is nil or default value of float64, return true.
IsEmptyObject check whether value is empty if value is nil or empty object, return true.
IsEmptyString check whether value is empty if value is nil or default value of string, return true.
ParseKindArray parse all array kind of value.
ParseKindMap parse map kind of value.
ParseKindValue parse all kind of value.
RandString is an function to gen a rand string.
Register is a function to register handler to http mux.
RemoveDupArray remove duplicate elements.

# Constants

A set of supported Field Kind.
A set of supported Field Kind.
A set of supported Field Kind.
A set of supported Field Kind.
A set of supported Field Kind.
A set of supported Field Kind.
A set of supported Field Kind.
A set of supported Field Kind.
A set of supported Field Kind.
A set of supported Field Kind.
A set of supported Field Kind.
A set of supported Field Kind.
A set of supported Field Kind.
A set of supported Field Kind.
A set of supported Field Kind.
A set of supported Field Kind.
A set of supported Field Kind.
A set of supported Field Kind.
A set of supported Field Kind.
A set of supported Field Kind.
A set of supported Field Kind.
A set of supported Field Kind.
A set of supported Field Kind.
A set of supported Field Kind.

# Variables

Log is a global log handle you can reassign Log to your own Logger which contains the methods Logger interface contains.

# Structs

ExtLog is the default Logger.
Field definition.
FieldSet is a structure to store DataStruct fields parsing result.
GlobalConfig is a config to init restful service.
Index describes the definition of an index.
IndexEnsuredMap cache to store index that has been ensured.
IndexEnsureList is a structure describes a list of indices to ensure.
IndexToEnsureStruct defines where and how to create the index.
Processor is a set of configurations and handlers of a Restful resource.
Rsp is a general returning structure for all request.
RspGetPageData is a general returning structure in `data` field for GetPage request.
SearchResponse is the rsp structure of es.

# Interfaces

Logger is an interface for logging.

# Type aliases

Handler is a template function for Restful Handler.