1 Star 0 Fork 0

Leng Shanshu / etris

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
api_server.go 6.20 KB
一键复制 编辑 原始数据 按行查看 历史
Leng Shanshu 提交于 2021-12-15 18:59 . remove access and statistics
package main
import (
stdCtx "context"
// "fmt"
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/versioning"
// "go.etcd.io/etcd/client/v3/naming/endpoints"
"gitee.com/lengss/boost/msar"
"log"
"path/filepath"
"strings"
"sync"
"time"
)
var registry msar.RegistryPlugin
func NewAPIServerApp() *iris.Application {
fName := "api"
app := iris.New()
//1. 错误自定义接管处理, 404页面, crash( panic ), 500 捕获
app.OnErrorCode(iris.StatusNotFound, notFound)
app.Use(MyRecover())
ac := makeAccessLog(fName)
// ac := makeRotateAccessLog(fName)
defer ac.Close()
// Register the middleware (UseRouter to catch http errors too).
app.UseRouter(ac.Handler)
// 2. log日志打印设置 :
lgfile := makeLogger(app, fName)
api := app.Party("/api")
// Optional, set version aliases (literal strings).
// We use `UseRouter` instead of `Use`
// to handle HTTP errors per version, but it's up to you.
api.UseRouter(versioning.Aliases(versioning.AliasMap{
// If no version provided by the client, default it to the "1.0.0".
versioning.Empty: "1.0.0",
// If a "latest" version is provided by the client,
// set the version to be compared to "3.0.0".
"latest": "3.0.0",
}))
tmpl := iris.HTML(filepath.Join(g_Configs.WebPath, "./demo"), ".html").Layout("layouts/layout.html")
tmpl.Reload(true)
app.RegisterView(tmpl)
// |----------------|
// | The fun begins |
// |----------------|
// Create a new Group, which is a compatible Party,
// based on version constraints.
v1 := versioning.NewGroup(api, ">=1.0.0 <2.0.0")
// To mark an API version as deprecated use the Deprecated method.
// Optionally, set custom view engine and path
// for templates based on the version.
// Register resources based on the version.
v1.Get("/hello", api_v1_hello)
v1.Post("/world", api_v1_world)
// Do the same for version 2 and version 3,
v2 := versioning.NewGroup(api, ">=2.0.0 <3.0.0")
v2.Get("/hello", api_v2_hello)
v2.Post("/world", api_v2_world)
// 5. 注册静态文件
app.Favicon(filepath.Join(g_Configs.WebPath, "/static/favicon.ico"))
app.HandleDir("/static", filepath.Join(g_Configs.WebPath, "./static"))
//其它初始化操作,比如数据库,seesion初始化
// 6. 关机时间设置,graceful shutdown
serverWG := new(sync.WaitGroup)
defer serverWG.Wait()
////////////////////////////////////////////////////////////
// etcd/mdns RegistryPluin
// etcd_clusters := []string{"127.0.0.1:7039"}
target := "service/api"
var err error
if len(g_Configs.Etcd) > 0 {
etcd_clusters := strings.Split(g_Configs.Etcd, ",")
registry, err = msar.NewEtcdRegistry(etcd_clusters, target, lgfile, irisConf.LogLevel)
} else {
registry, err = msar.NewMDNSRegistry(target, lgfile, irisConf.LogLevel)
}
if err != nil {
log.Fatalf("register %s failed:%v", target, err)
}
// registry.AccessPrepare(irisConf.Other["Accesses"].(string))
var keepAlive_ttl int64 = 60
err = registry.RegistService(int(g_Configs.ListenAddr), keepAlive_ttl)
if err != nil {
log.Fatalf("register %s failed:%v", target, err)
}
// etcd registry
//////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
iris.RegisterOnInterrupt(func() {
serverWG.Add(1)
defer serverWG.Done()
// do something
ctx, cancel := stdCtx.WithTimeout(stdCtx.Background(), 30*time.Second)
defer cancel()
app.Logger().Info("graceful shutdown DB now !!!")
/////////////////////////////////////////////////////////////
registry.Close()
/////////////////////////////////////////////////////////////
app.Shutdown(ctx)
})
// 7. 启动服务
return app
// return app.Listen(fmt.Sprintf(":%s", *port), iris.WithConfiguration(irisConf))
}
func api_v1_world(ctx iris.Context) {
req := ctx.Request()
reqAddr := req.RemoteAddr
// err := registry.AccessIncr(strings.Split(reqAddr, ":")[0])
title := ctx.PostValueDefault("title", "default")
content := ctx.PostValueDefault("content", "default")
var retv Message
retv = Message{Id: 1, Title: title, Content: content, Created: time.Now()}
ctype := ctx.GetHeader("Accept")
conn := ctx.GetHeader("Connection")
ctx.Application().Logger().Debugf("Accept = %s, connection=%v , RemoteAddr = %s", ctype, conn, reqAddr)
ctx.Application().Logger().Debugf("%v", retv)
ctx.Negotiation().JSON(retv).XML(retv).MsgPack(retv)
_, err := ctx.Negotiate(nil)
if err != nil {
ctx.Application().Logger().Debugf("Negotiate error, %v", err)
}
}
func api_v1_hello(ctx iris.Context) {
req := ctx.Request()
reqAddr := req.RemoteAddr
var retv Message
retv = Message{Id: 2, Title: "title hello", Content: "This is content test, Verion=1.0.0", Created: time.Now()}
ctype := ctx.GetHeader("Accept")
conn := ctx.GetHeader("Connection")
ctx.Application().Logger().Debugf("Accept = %s, connection=%v , RemoteAddr = %s", ctype, conn, reqAddr)
ctx.Negotiation().JSON(retv).XML(retv).MsgPack(retv)
_, err := ctx.Negotiate(nil)
if err != nil {
ctx.Application().Logger().Debugf("Negotiate error, %v", err)
}
}
func api_v2_world(ctx iris.Context) {
req := ctx.Request()
reqAddr := req.RemoteAddr
title := ctx.PostValueDefault("title", "default")
content := ctx.PostValueDefault("content", "default")
var retv Message
retv = Message{Id: 3, Title: title, Content: content, Created: time.Now()}
ctype := ctx.GetHeader("Accept")
conn := ctx.GetHeader("Connection")
ctx.Application().Logger().Debugf("Accept = %s, connection=%v , RemoteAddr = %s", ctype, conn, reqAddr)
ctx.Application().Logger().Debugf("%v", retv)
ctx.Negotiation().JSON(retv).XML(retv).MsgPack(retv)
_, err := ctx.Negotiate(nil)
if err != nil {
ctx.Application().Logger().Debugf("Negotiate error, %v", err)
}
}
func api_v2_hello(ctx iris.Context) {
req := ctx.Request()
reqAddr := req.RemoteAddr
var retv Message
retv = Message{Id: 4, Title: "title hello V2", Content: "This is content test. Version=2.0.0", Created: time.Now()}
ctype := ctx.GetHeader("Accept")
conn := ctx.GetHeader("Connection")
ctx.Application().Logger().Debugf("Accept = %s, connection=%v , RemoteAddr = %s", ctype, conn, reqAddr)
ctx.Negotiation().JSON(retv).XML(retv).MsgPack(retv)
_, err := ctx.Negotiate(nil)
if err != nil {
ctx.Application().Logger().Debugf("Negotiate error, %v", err)
// ctx.Writef("%v", err)
}
}
Go
1
https://gitee.com/lengss/etris.git
git@gitee.com:lengss/etris.git
lengss
etris
etris
master

搜索帮助