golang实现MongoDB文档和元数据访问的REST服务插件库Mora的使用
Golang实现MongoDB文档和元数据访问的REST服务插件库Mora的使用
Mora - Mongo Rest API

REST server for accessing MongoDB documents and meta data
Mora是一个基于Golang的REST服务插件库,用于访问MongoDB文档和元数据。
文档查询参数
在查询集合时,可以使用以下参数:
query - 使用Mongo shell语法,例如 {"size":42}
limit - 返回结果的最大文档数
skip - 结果集的偏移量
fields - 逗号分隔的(路径点)字段名列表
sort - 逗号分隔的(路径点)字段名列表
extended_json - 设置为"true"以MongoDB扩展JSON格式返回响应
使用示例
列出别名
$ curl 'http://127.0.0.1:8181/docs/' \
-D - \
-H 'Accept: application/json'
HTTP/1.1 200 OK
Content-Type: application/json
Date: Tue, 22 Apr 2014 07:06:30 GMT
Content-Length: 61
{
"success": true,
"data": [
"test",
"local"
]
}
列出数据库
$ curl 'http://127.0.0.1:8181/docs/local/' \
-D - \
-H 'Accept: application/json'
HTTP/1.1 200 OK
Content-Type: application/json
Date: Tue, 22 Apr 2014 07:07:11 GMT
Content-Length: 61
{
"success": true,
"data": [
"local",
"use1"
]
}
列出集合
$ curl 'http://127.0.0.1:8181/docs/local/local' \
-D - \
-H 'Accept: application/json'
HTTP/1.1 200 OK
Content-Type: application/json
Date: Tue, 22 Apr 2014 07:24:10 GMT
Content-Length: 98
{
"success": true,
"data": [
"new-collection",
"startup_log",
"system.indexes"
]
}
插入文档
$ curl 'http://127.0.0.1:8181/docs/local/local/new-collection/document-id' \
-D - \
-X POST \
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
--data '{"title": "Some title", "content": "document content"}'
HTTP/1.1 201 Created
Content-Location: /docs/local/local/new-collection/document-id
Content-Type: application/json
Date: Tue, 22 Apr 2014 07:23:33 GMT
Content-Length: 116
{
"success": true,
"data": {
"created": true,
"url": "/docs/local/local/new-collection/document-id"
}
}
查找文档
$ curl 'http://127.0.0.1:8181/docs/local/local/new-collection/document-id' \
-D - \
-H 'Accept: application/json'
HTTP/1.1 200 OK
Content-Type: application/json
Date: Tue, 22 Apr 2014 07:32:33 GMT
Content-Length: 123
{
"success": true,
"data": {
"_id": "document-id",
"content": "document content",
"title": "Some title"
}
}
查找多个文档
$ curl 'http://127.0.0.1:8181/docs/local/local/new-collection?limit=1&skip=1' \
-D - \
-H 'Accept: application/json'
HTTP/1.1 200 OK
Content-Type: application/json
Date: Wed, 23 Apr 2014 23:18:39 GMT
Content-Length: 387
{
"success": true,
"prev_url": "/docs/local/local/new-collection?limit=1&skip=0",
"next_url": "/docs/local/local/new-collection?limit=1&skip=2",
"data": [
{
"_id": "535849cfb734f91cdc000002",
"content": "document content",
"title": "Some title"
}
]
}
更新文档
$ curl 'http://127.0.0.1:8181/docs/local/local/new-collection/document-id' \
-D - \
-X PUT \
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
--data '{"title": "New title"}'
HTTP/1.1 200 OK
Content-Location: /docs/local/local/new-collection/document-id
Content-Type: application/json
Date: Tue, 22 Apr 2014 06:37:02 GMT
Content-Length: 133
{
"success": true,
"data": {
"created": false,
"url": "/docs/local/local/new-collection/document-id"
}
}
更新多个文档
$ curl 'http://127.0.0.1:8181/docs/local/local/new-collection' \
-D - \
-X PUT \
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
--data '{"$set": {"title": "New title"}}'
HTTP/1.1 200 OK
Content-Type: application/json
Date: Wed, 23 Apr 2014 23:33:11 GMT
Content-Length: 22
{
"success": true
}
删除文档
$ curl 'http://127.0.0.1:8181/docs/local/local/new-collection/document-id' \
-D - \
-X DELETE \
-H 'Accept: application/json'
HTTP/1.1 200 OK
Content-Type: application/json
Date: Tue, 22 Apr 2014 07:42:47 GMT
Content-Length: 22
{
"success": true
}
删除集合
$ curl 'http://127.0.0.1:8181/docs/local/local/new-collection' \
-D - \
-X DELETE \
-H 'Accept: application/json'
HTTP/1.1 200 OK
Content-Type: application/json
Date: Tue, 22 Apr 2014 07:43:24 GMT
Content-Length: 22
{
"success": true
}
统计信息
数据库统计
$ curl http://127.0.0.1:8181/stats/local/local -D -
HTTP/1.1 200 OK
Content-Type: application/json
Date: Tue, 22 Apr 2014 08:17:46 GMT
Content-Length: 341
{
"success": true,
"data": {
"avgObjSize": 595.6,
"collections": 3,
"dataFileVersion": {
"major": 4,
"minor": 5
},
"dataSize": 5956,
"db": "local",
"fileSize": 67108864,
"indexSize": 0,
"indexes": 0,
"nsSizeMB": 16,
"numExtents": 3,
"objects": 10,
"ok": 1,
"storageSize": 10502144
}
}
集合统计
$ curl http://127.0.0.1:8181/stats/local/local/startup_log -D -
HTTP/1.1 200 OK
Content-Type: application/json
Date: Tue, 22 Apr 2014 08:18:16 GMT
Content-Length: 389
{
"success": true,
"data": {
"avgObjSize": 728,
"capped": true,
"count": 8,
"indexSizes": {},
"lastExtentSize": 10485760,
"max": 9223372036854775807,
"nindexes": 0,
"ns": "local.startup_log",
"numExtents": 1,
"ok": 1,
"paddingFactor": 1,
"size": 5824,
"storageSize": 10485760,
"systemFlags": 0,
"totalIndexSize": 0,
"userFlags": 0
}
}
从源码安装
go get -u github.com/emicklei/mora
创建发布
sh release.sh
配置
Mora使用简单的属性文件来指定主机、端口、别名和其他选项。
# listener info is required
http.server.host=localhost
http.server.port=8181
# enable cross site requests
http.server.cors=true
# for swagger support (optional)
swagger.path=/apidocs/
swagger.file.path=./swagger-ui/dist
# mongo instances are listed here; specify an alias for each
mongod.{alias}.host=localhost
mongod.{alias}.port=27017
# initial and operational timeout in seconds
mongod.{alias}.timeout=5
# optional authentication
mongod.{alias}.username=
mongod.{alias}.password=
mongod.{alias}.database=
# read preference mode
# supported options (case-insensitive): https://godoc.org/gopkg.in/mgo.v2#Mode
mongod.{alias}.mode=primary
# alternatively, a mongodb connection string uri can be used instead
# supported options: https://godoc.org/gopkg.in/mgo.v2#Dial
mongod.{alias}.uri=mongodb://myuser:mypass@localhost:40001,otherhost:40001/mydb
# enable /stats/ endpoint
mora.statistics.enable=true
运行
$ mora -config mora.properties
Swagger
Swagger UI会自动显示API文档和测试界面。
© 2013, MIT License
更多关于golang实现MongoDB文档和元数据访问的REST服务插件库Mora的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html
更多关于golang实现MongoDB文档和元数据访问的REST服务插件库Mora的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
Mora: 一个轻量级的MongoDB REST服务插件库
Mora是一个用Go语言编写的轻量级库,它能够快速将MongoDB数据库转换为RESTful API服务。下面我将介绍如何使用Mora来实现MongoDB文档和元数据的REST访问。
安装Mora
首先,安装Mora库:
go get github.com/emicklei/mora
基本使用示例
下面是一个简单的Mora使用示例:
package main
import (
"log"
"net/http"
"github.com/emicklei/mora"
"gopkg.in/mgo.v2"
)
func main() {
// 创建Mora实例
m := mora.New("mora-example")
// 配置MongoDB连接
mongoSession, err := mgo.Dial("localhost")
if err != nil {
log.Fatal(err)
}
defer mongoSession.Close()
// 设置MongoDB会话
m.SetSession(mongoSession)
// 配置路由
http.Handle("/mora/", m)
// 启动服务器
log.Println("Mora server running on http://localhost:8080/mora")
log.Fatal(http.ListenAndServe(":8080", nil))
}
API端点说明
启动服务后,Mora会提供以下REST端点:
-
数据库列表:
GET /mora/
-
集合列表:
GET /mora/{db}
-
文档操作:
GET /mora/{db}/{collection} // 查询文档 POST /mora/{db}/{collection} // 插入文档 PUT /mora/{db}/{collection}/{id} // 更新文档 DELETE /mora/{db}/{collection}/{id} // 删除文档 GET /mora/{db}/{collection}/{id} // 获取单个文档
高级配置
Mora支持多种配置选项:
// 创建带有配置的Mora实例
m := mora.NewWithConfig(mora.Config{
BasePath: "/api/",
SessionTimeout: 60 * time.Second,
MaxResultSize: 100,
})
查询参数
Mora支持多种查询参数:
q
: 查询条件 (JSON格式)fields
: 返回字段 (逗号分隔)skip
: 跳过文档数limit
: 返回文档数限制sort
: 排序字段
示例查询:
GET /mora/mydb/users?q={"age":{"$gt":18}}&fields=name,age&sort=-age&limit=10
自定义中间件
Mora支持添加中间件:
// 认证中间件示例
func authMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("X-API-KEY") != "secret" {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
// 添加中间件
m.Use(authMiddleware)
元数据访问
Mora也提供了一些元数据访问端点:
-
数据库统计信息:
GET /mora/{db}/$stats
-
集合统计信息:
GET /mora/{db}/{collection}/$stats
-
索引信息:
GET /mora/{db}/{collection}/$indexes
性能优化建议
-
使用连接池:
mongoSession.SetPoolLimit(100)
-
限制结果大小:
m.SetMaxResultSize(1000) // 限制每次查询最多返回1000条记录
-
使用适当的索引提高查询性能
错误处理
Mora返回标准的HTTP状态码:
- 200 OK - 成功
- 400 Bad Request - 请求参数错误
- 404 Not Found - 资源不存在
- 500 Internal Server Error - 服务器错误
总结
Mora是一个简单而强大的库,可以快速为MongoDB创建RESTful接口。它适合需要快速构建原型或为现有MongoDB数据库提供REST访问的场景。虽然它不像MongoDB官方REST接口那样功能全面,但它更加轻量级且易于定制。
对于生产环境,你可能需要考虑添加更多的安全措施,如身份验证、速率限制和更详细的日志记录。