All Projects → af913337456 → XGoServer

af913337456 / XGoServer

Licence: other
一个基础性、模块完整且安全可靠的轻量级 Go 服务端框架

Programming Languages

go
31211 projects - #10 most used programming language
scala
5932 projects

Projects that are alternatives of or similar to XGoServer

dingtalk-encrypt
dingTalk encrypt Node Version. 钉钉的非官方nodejs版AES加解密库 sdk
Stars: ✭ 16 (-23.81%)
Mutual labels:  encrypt
Seedshift
Plausibly deniable steganographic encryption of BIP-39 mnemonic seed words with a date shift cipher
Stars: ✭ 21 (+0%)
Mutual labels:  encrypt
IoT-Technical-Guide
🐝 IoT Technical Guide --- 从零搭建高性能物联网平台及物联网解决方案和Thingsboard源码分析 ✨ ✨ ✨ (IoT Platform, SaaS, MQTT, CoAP, HTTP, Modbus, OPC, WebSocket, 物模型,Protobuf, PostgreSQL, MongoDB, Spring Security, OAuth2, RuleEngine, Kafka, Docker)
Stars: ✭ 2,565 (+12114.29%)
Mutual labels:  token
ethereum-contracts
Knowledge Ethereum Smart Contracts
Stars: ✭ 41 (+95.24%)
Mutual labels:  token
every-eos
Decentralized exchange based on eos.io
Stars: ✭ 20 (-4.76%)
Mutual labels:  token
kirby3-instagram
Kirby 3 Plugin to call Instagram (or any other) API Endpoints
Stars: ✭ 20 (-4.76%)
Mutual labels:  token
Windows-Python-RAT
A New Microsoft Windows Remote Administrator Tool [RAT] with Python by Sir.4m1R.
Stars: ✭ 70 (+233.33%)
Mutual labels:  token
eXperDB-Management
eXperDB-Management is a integrated management tool for PostgreSQL(for efficient operation and management).
Stars: ✭ 38 (+80.95%)
Mutual labels:  encrypt
OSAPI
👋 OSAPI 是依靠通用性后台管理平台搭建的API管理平台,基于 vue3、Nestjs 技术栈实现,包含 RBAC 角色权限模块、数据展示、编辑等模块。
Stars: ✭ 32 (+52.38%)
Mutual labels:  token
nodejs-wechat
基于nodejs开发微信公众号
Stars: ✭ 13 (-38.1%)
Mutual labels:  token
CoinMarketCap-Desktop
A simple desktop wrapper for CoinMarketCap
Stars: ✭ 21 (+0%)
Mutual labels:  token
google-translate-tk
Calculate google translate's token(tk) by Golang
Stars: ✭ 33 (+57.14%)
Mutual labels:  token
ASPNETcoreAngularJWT
Angular in ASP.NET Core with JWT solution by systemjs
Stars: ✭ 48 (+128.57%)
Mutual labels:  token
node-dev-server
基于Express,Sequelize、IIS的MVC新手项目
Stars: ✭ 12 (-42.86%)
Mutual labels:  token
auth-flow-react-apollo-saga
Full stack login/register flow with React, Apollo, Redux, Redux-saga and MongoDB.
Stars: ✭ 22 (+4.76%)
Mutual labels:  token
ethereum-dex
Decentralized exchange implementation for the 0xcert protocol on the Ethereum blockchain.
Stars: ✭ 18 (-14.29%)
Mutual labels:  token
restify-jwt-community
Restify middleware that validates a JsonWebToken
Stars: ✭ 24 (+14.29%)
Mutual labels:  token
horse-jwt
Middleware for JWT in HORSE
Stars: ✭ 39 (+85.71%)
Mutual labels:  token
brauzie
Awesome CLI for fetching JWT tokens for OAuth2.0 clients
Stars: ✭ 14 (-33.33%)
Mutual labels:  token
EasyTokenGenerator
This repo aims to dynamically and simply generate tokens in Token Based systems.
Stars: ✭ 15 (-28.57%)
Mutual labels:  token

作者:林冠宏 / 指尖下的幽灵

掘金:https://juejin.im/user/587f0dfe128fe100570ce2d8

博客:http://www.cnblogs.com/linguanh/


一个基础性、模块完整且安全可靠的服务端框架

你可以使用它

  • 简单快速搭建自己的服务端
  • 其他高级模块拓展等

具备的

  • Token模块,jwt
  • 加解密模块,cipher-AES,可自行拓展其他
  • 日志模块,alecthomas/log4go
  • 路由模块,gorilla/mux
  • 硬存储 / 软存储 采用 xorm 框架
  • 服务端通用的输出数据结构的整合,例如 json
  • 各模块对应的单元测试例子
如果你想直接输出一条 json 给客户端,这样子
func main()  {
    router := new (mux.Router)
    router.HandleFunc("/",test2).Methods("GET")
    core.HttpListen(router)
}
func test2(w http.ResponseWriter,r *http.Request)  {
    // 非常简单的例子, 操作放在内部 , 可以使用 request 来获取自己的参数,再直接组织输出
    core.HandlerMapWithOutputJson(w, func() map[string]interface{} {
    	m :=  map[string]interface{}{}
    	m["msg"] = "blow me a kiss"
    	return m
    })
}
// 结果 : {"msg":"blow me a kiss"}
令牌机制
// core.ApiNormalHandler 不要求在请求头中传递 Token
router.Handle("/fuck",core.ApiNormalHandler(getToken)).Methods("GET")

// core.ApiRequestTokenHandler 要求在请求头中带上 Token
router.Handle("/check",core.ApiRequestTokenHandler(handleToken)).Methods("GET")

// 定义对应上下文的路由方法
func getToken(req *core.ReqContext)  {
    // 从 req 中读出内容
	core.HandlerMapWithOutputJson(req.W, func() map[string]interface{} {
		tokenStr,_ := core.BuildDefaultToken(func(tokenData *core.TokenData) {
			tokenData.UserId = "123456"
			tokenData.Roles  = "normal"
		})
		return util.GetCommonSuccess(tokenStr)
	})
}
与数据库交互
func test3(w http.ResponseWriter,r *http.Request)  {
	core.HandlerMapWithOutputJson(w, func() map[string]interface{} {
		// 插入一条评论
		item := &model.Comment{
			Id	:util.NewId(),         // 评论 id
			UserId	:"123456",             // 评论人 id
			Name	:"LinGuanHong",        // 评论人名称
			Content	:"hello word",         // 评论内容
		}
		affect,_ := core.Engine.Insert(item)  // 执行插入,传入 struct 引用
		m :=  map[string]interface{}{}
		if affect > 0 {
			m["ret"] = "insert success"
			comments := make([]model.Comment, 0)
			core.Engine.Find(&comments)   // select 出来,获取所有评论输出
			m["msg"] = comments
		}else{
			m["ret"] = "insert failed"
		}
		return m
	})
}

输出的结果是:
{
  "msg": [
    {
      "id": "1kubpgh9pprrucy11e456fyytw",
      "UserId": "123456",
      "name": "LinGuanHong",
      "content": "hello word"
    }
  ],
  "ret": "insert success"
}

使用流程

目录如下

---- config
---- core
---- model
---- threeLibs
---- util
---- server.go

1 在 config 放置配置文件

  • 服务端配置 json 文件 -- server.json,
  • 日志配置文件 -- log.json 例如下面的,他们都会在运行程序后会自动解析和读取

2 threeLibs 目录放置了依赖的第三方库,例如 xorm,不需要你再去 go get

3 model 放置数据实体 struct

{
  "Host": "127.0.0.1",
  "Port": ":8884",
  "FilePort":":8885",
  "DbName":"lgh",
  "DbUser":"root",
  "DbPw":"123456",
  "DbPort":"3306"
}
{
  "EnableConsole": true,
  "ConsoleLevel": "DEBUG",
  "EnableFile": true,
  "FileLevel": "INFO",
  "FileFormat": "",
  "FileLocation": ""
}

从一个最基础的例子开始:

func main()  {
    router := new (mux.Router)
    router.HandleFunc("/",test).Methods("GET")
    /** 在下面添加你的路由 */
    /** add your routine func below */
    core.HttpListen(router)  // 简单的 http 监听,当然也提供了 https
}
func test(w http.ResponseWriter,r *http.Request)  {
    fmt.Fprintf(w,"======= hello world! =======")
}
// http 监听
func HttpListen(router *mux.Router)  {
	SimpleInit()  // 此处自动初始化 ---------- ①
	url := config.ServerConfig.Host+config.ServerConfig.Port
	util.LogInfo("服务启动于 : "+url)
	err := http.ListenAndServe(url,router)
	if err !=nil {
		util.LogInfo("http error ===> : "+err.Error())
		return
	}
}
// 绑定配置 json 的信息 以及 初始化 xorm mysql数据库引擎
func SimpleInit() {
	config.BindServerConfig("server.json","log.json")
	fmt.Println("BindServerConfig ==================>","success")
	config.ConfigureLog(&config.LogConfig)
	CreateDefaultMysqlEngine(
		"mysql",
		config.ServerConfig.DbUser,
		config.ServerConfig.DbPw,
		config.ServerConfig.DbName)
}

服务端通用的输出数据结构的整合函数组

type FinalResult struct {
	Data interface{}
}

type RetChannel chan FinalResult

func HandlerStruct(handle func() interface{}) *interface{} {
	RetChannel := make(RetChannel, 1)
	go func() {
		result := FinalResult{}
		data := handle()
		result.Data = &data
		RetChannel <- result
		close(RetChannel)
	}()
	ret := <-RetChannel
	return ret.Data.(*interface{})
}

func HandlerMap(handle func() map[string]interface{}) *map[string]interface{} {
	RetChannel := make(RetChannel, 1)
	go func() {
		result := FinalResult{}
		data := handle()
		result.Data = &data
		RetChannel <- result
		close(RetChannel)
	}()
	ret := <-RetChannel
	return ret.Data.(*map[string]interface{})
}

// 还有
// HandlerStructWithOutputXML  // XML 的输出格式
// HandlerStructWithOutputString

func HandlerStructWithOutputJson(w http.ResponseWriter,handle func() interface{})  {
	RetChannel := make(RetChannel, 1)
	go func() {
		result := FinalResult{}
		data := handle()
		result.Data = &data
		RetChannel <- result
		close(RetChannel)
	}()
	ret := <-RetChannel
	mapRet := ret.Data.(*interface{})
	util.RenderJson(w,mapRet)
}

func HandlerMapWithOutputJson(w http.ResponseWriter,handle func() map[string]interface{}){
	RetChannel := make(RetChannel, 1)
	go func() {
		result := FinalResult{}
		data := handle()
		result.Data = &data
		RetChannel <- result
		close(RetChannel)
	}()
	ret := <-RetChannel
	mapRet := ret.Data.(*map[string]interface{})
	util.RenderJson(w,mapRet)
}

就介绍这么多了

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].