替换ioutil包为os/io包,它在1.16开始被弃用

This commit is contained in:
orgin
2022-08-17 14:28:01 +08:00
parent 84f3429564
commit 1520dae223
4 changed files with 168 additions and 171 deletions

View File

@@ -5,7 +5,7 @@ import (
"github.com/duanhf2012/origin/log" "github.com/duanhf2012/origin/log"
"github.com/duanhf2012/origin/rpc" "github.com/duanhf2012/origin/rpc"
jsoniter "github.com/json-iterator/go" jsoniter "github.com/json-iterator/go"
"io/ioutil" "os"
"strings" "strings"
) )
@@ -18,7 +18,7 @@ type NodeInfoList struct {
func (cls *Cluster) ReadClusterConfig(filepath string) (*NodeInfoList, error) { func (cls *Cluster) ReadClusterConfig(filepath string) (*NodeInfoList, error) {
c := &NodeInfoList{} c := &NodeInfoList{}
d, err := ioutil.ReadFile(filepath) d, err := os.ReadFile(filepath)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -33,7 +33,7 @@ func (cls *Cluster) ReadClusterConfig(filepath string) (*NodeInfoList, error) {
func (cls *Cluster) readServiceConfig(filepath string) (interface{}, map[string]interface{}, map[int]map[string]interface{}, error) { func (cls *Cluster) readServiceConfig(filepath string) (interface{}, map[string]interface{}, map[int]map[string]interface{}, error) {
c := map[string]interface{}{} c := map[string]interface{}{}
//读取配置 //读取配置
d, err := ioutil.ReadFile(filepath) d, err := os.ReadFile(filepath)
if err != nil { if err != nil {
return nil, nil, nil, err return nil, nil, nil, err
} }
@@ -69,7 +69,7 @@ func (cls *Cluster) readLocalClusterConfig(nodeId int) ([]NodeInfo, []NodeInfo,
var nodeInfoList []NodeInfo var nodeInfoList []NodeInfo
var masterDiscoverNodeList []NodeInfo var masterDiscoverNodeList []NodeInfo
clusterCfgPath := strings.TrimRight(configDir, "/") + "/cluster" clusterCfgPath := strings.TrimRight(configDir, "/") + "/cluster"
fileInfoList, err := ioutil.ReadDir(clusterCfgPath) fileInfoList, err := os.ReadDir(clusterCfgPath)
if err != nil { if err != nil {
return nil, nil, fmt.Errorf("Read dir %s is fail :%+v", clusterCfgPath, err) return nil, nil, fmt.Errorf("Read dir %s is fail :%+v", clusterCfgPath, err)
} }
@@ -111,7 +111,7 @@ func (cls *Cluster) readLocalClusterConfig(nodeId int) ([]NodeInfo, []NodeInfo,
func (cls *Cluster) readLocalService(localNodeId int) error { func (cls *Cluster) readLocalService(localNodeId int) error {
clusterCfgPath := strings.TrimRight(configDir, "/") + "/cluster" clusterCfgPath := strings.TrimRight(configDir, "/") + "/cluster"
fileInfoList, err := ioutil.ReadDir(clusterCfgPath) fileInfoList, err := os.ReadDir(clusterCfgPath)
if err != nil { if err != nil {
return fmt.Errorf("Read dir %s is fail :%+v", clusterCfgPath, err) return fmt.Errorf("Read dir %s is fail :%+v", clusterCfgPath, err)
} }

View File

@@ -8,9 +8,9 @@ import (
"github.com/duanhf2012/origin/log" "github.com/duanhf2012/origin/log"
"github.com/duanhf2012/origin/profiler" "github.com/duanhf2012/origin/profiler"
"github.com/duanhf2012/origin/service" "github.com/duanhf2012/origin/service"
"github.com/duanhf2012/origin/util/timer"
"github.com/duanhf2012/origin/util/buildtime" "github.com/duanhf2012/origin/util/buildtime"
"io/ioutil" "github.com/duanhf2012/origin/util/timer"
"io"
slog "log" slog "log"
"net/http" "net/http"
_ "net/http/pprof" _ "net/http/pprof"
@@ -34,30 +34,30 @@ var logPath string
func init() { func init() {
closeSig = make(chan bool,1) closeSig = make(chan bool, 1)
sig = make(chan os.Signal, 3) sig = make(chan os.Signal, 3)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM,syscall.Signal(10)) signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM, syscall.Signal(10))
console.RegisterCommandBool("help",false,"<-help> This help.",usage) console.RegisterCommandBool("help", false, "<-help> This help.", usage)
console.RegisterCommandString("name","","<-name nodeName> Node's name.",setName) console.RegisterCommandString("name", "", "<-name nodeName> Node's name.", setName)
console.RegisterCommandString("start","","<-start nodeid=nodeid> Run originserver.",startNode) console.RegisterCommandString("start", "", "<-start nodeid=nodeid> Run originserver.", startNode)
console.RegisterCommandString("stop","","<-stop nodeid=nodeid> Stop originserver process.",stopNode) console.RegisterCommandString("stop", "", "<-stop nodeid=nodeid> Stop originserver process.", stopNode)
console.RegisterCommandString("config","","<-config path> Configuration file path.",setConfigPath) console.RegisterCommandString("config", "", "<-config path> Configuration file path.", setConfigPath)
console.RegisterCommandString("console", "", "<-console true|false> Turn on or off screen log output.", openConsole) console.RegisterCommandString("console", "", "<-console true|false> Turn on or off screen log output.", openConsole)
console.RegisterCommandString("loglevel", "debug", "<-loglevel debug|release|warning|error|fatal> Set loglevel.", setLevel) console.RegisterCommandString("loglevel", "debug", "<-loglevel debug|release|warning|error|fatal> Set loglevel.", setLevel)
console.RegisterCommandString("logpath", "", "<-logpath path> Set log file path.", setLogPath) console.RegisterCommandString("logpath", "", "<-logpath path> Set log file path.", setLogPath)
console.RegisterCommandString("pprof","","<-pprof ip:port> Open performance analysis.",setPprof) console.RegisterCommandString("pprof", "", "<-pprof ip:port> Open performance analysis.", setPprof)
} }
func usage(val interface{}) error{ func usage(val interface{}) error {
ret := val.(bool) ret := val.(bool)
if ret == false { if ret == false {
return nil return nil
} }
if len(buildtime.GetBuildDateTime())>0 { if len(buildtime.GetBuildDateTime()) > 0 {
fmt.Fprintf(os.Stderr, "Welcome to Origin(build info: %s)\nUsage: originserver [-help] [-start node=1] [-stop] [-config path] [-pprof 0.0.0.0:6060]...\n",buildtime.GetBuildDateTime()) fmt.Fprintf(os.Stderr, "Welcome to Origin(build info: %s)\nUsage: originserver [-help] [-start node=1] [-stop] [-config path] [-pprof 0.0.0.0:6060]...\n", buildtime.GetBuildDateTime())
}else{ } else {
fmt.Fprintf(os.Stderr, "Welcome to Origin\nUsage: originserver [-help] [-start node=1] [-stop] [-config path] [-pprof 0.0.0.0:6060]...\n") fmt.Fprintf(os.Stderr, "Welcome to Origin\nUsage: originserver [-help] [-start node=1] [-stop] [-config path] [-pprof 0.0.0.0:6060]...\n")
} }
@@ -71,28 +71,28 @@ func setName(val interface{}) error {
func setPprof(val interface{}) error { func setPprof(val interface{}) error {
listenAddr := val.(string) listenAddr := val.(string)
if listenAddr==""{ if listenAddr == "" {
return nil return nil
} }
go func(){ go func() {
err := http.ListenAndServe(listenAddr, nil) err := http.ListenAndServe(listenAddr, nil)
if err != nil { if err != nil {
panic(fmt.Errorf("%+v",err)) panic(fmt.Errorf("%+v", err))
} }
}() }()
return nil return nil
} }
func setConfigPath(val interface{}) error{ func setConfigPath(val interface{}) error {
configPath := val.(string) configPath := val.(string)
if configPath==""{ if configPath == "" {
return nil return nil
} }
_, err := os.Stat(configPath) _, err := os.Stat(configPath)
if err != nil { if err != nil {
return fmt.Errorf("Cannot find file path %s",configPath) return fmt.Errorf("Cannot find file path %s", configPath)
} }
cluster.SetConfigDir(configPath) cluster.SetConfigDir(configPath)
@@ -100,16 +100,16 @@ func setConfigPath(val interface{}) error{
return nil return nil
} }
func getRunProcessPid(nodeId int) (int,error) { func getRunProcessPid(nodeId int) (int, error) {
f, err := os.OpenFile(fmt.Sprintf("%s_%d.pid",os.Args[0],nodeId), os.O_RDONLY, 0600) f, err := os.OpenFile(fmt.Sprintf("%s_%d.pid", os.Args[0], nodeId), os.O_RDONLY, 0600)
defer f.Close() defer f.Close()
if err!= nil { if err != nil {
return 0,err return 0, err
} }
pidByte,errs := ioutil.ReadAll(f) pidByte, errs := io.ReadAll(f)
if errs!=nil { if errs != nil {
return 0,errs return 0, errs
} }
return strconv.Atoi(string(pidByte)) return strconv.Atoi(string(pidByte))
@@ -117,13 +117,13 @@ func getRunProcessPid(nodeId int) (int,error) {
func writeProcessPid(nodeId int) { func writeProcessPid(nodeId int) {
//pid //pid
f, err := os.OpenFile(fmt.Sprintf("%s_%d.pid",os.Args[0],nodeId), os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0600) f, err := os.OpenFile(fmt.Sprintf("%s_%d.pid", os.Args[0], nodeId), os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0600)
defer f.Close() defer f.Close()
if err != nil { if err != nil {
fmt.Println(err.Error()) fmt.Println(err.Error())
os.Exit(-1) os.Exit(-1)
} else { } else {
_,err=f.Write([]byte(fmt.Sprintf("%d",os.Getpid()))) _, err = f.Write([]byte(fmt.Sprintf("%d", os.Getpid())))
if err != nil { if err != nil {
fmt.Println(err.Error()) fmt.Println(err.Error())
os.Exit(-1) os.Exit(-1)
@@ -135,28 +135,28 @@ func GetNodeId() int {
return nodeId return nodeId
} }
func initNode(id int){ func initNode(id int) {
//1.初始化集群 //1.初始化集群
nodeId = id nodeId = id
err := cluster.GetCluster().Init(GetNodeId(),Setup) err := cluster.GetCluster().Init(GetNodeId(), Setup)
if err != nil { if err != nil {
log.SFatal("read system config is error ",err.Error()) log.SFatal("read system config is error ", err.Error())
} }
err = initLog() err = initLog()
if err != nil{ if err != nil {
return return
} }
//2.setup service //2.setup service
for _,s := range preSetupService { for _, s := range preSetupService {
//是否配置的service //是否配置的service
if cluster.GetCluster().IsConfigService(s.GetName()) == false { if cluster.GetCluster().IsConfigService(s.GetName()) == false {
continue continue
} }
pServiceCfg := cluster.GetCluster().GetServiceCfg(s.GetName()) pServiceCfg := cluster.GetCluster().GetServiceCfg(s.GetName())
s.Init(s,cluster.GetRpcClient,cluster.GetRpcServer,pServiceCfg) s.Init(s, cluster.GetRpcClient, cluster.GetRpcServer, pServiceCfg)
service.Setup(s) service.Setup(s)
} }
@@ -165,14 +165,14 @@ func initNode(id int){
service.Init(closeSig) service.Init(closeSig)
} }
func initLog() error{ func initLog() error {
if logPath == ""{ if logPath == "" {
setLogPath("./log") setLogPath("./log")
} }
localnodeinfo := cluster.GetCluster().GetLocalNodeInfo() localnodeinfo := cluster.GetCluster().GetLocalNodeInfo()
filepre := fmt.Sprintf("%s_%d_", localnodeinfo.NodeName, localnodeinfo.NodeId) filepre := fmt.Sprintf("%s_%d_", localnodeinfo.NodeName, localnodeinfo.NodeId)
logger,err := log.New(logLevel,logPath,filepre,slog.LstdFlags|slog.Lshortfile,10) logger, err := log.New(logLevel, logPath, filepre, slog.LstdFlags|slog.Lshortfile, 10)
if err != nil { if err != nil {
fmt.Printf("cannot create log file!\n") fmt.Printf("cannot create log file!\n")
return err return err
@@ -183,8 +183,8 @@ func initLog() error{
func Start() { func Start() {
err := console.Run(os.Args) err := console.Run(os.Args)
if err!=nil { if err != nil {
fmt.Printf("%+v\n",err) fmt.Printf("%+v\n", err)
return return
} }
} }
@@ -196,19 +196,19 @@ func stopNode(args interface{}) error {
return nil return nil
} }
sParam := strings.Split(param,"=") sParam := strings.Split(param, "=")
if len(sParam) != 2 { if len(sParam) != 2 {
return fmt.Errorf("invalid option %s",param) return fmt.Errorf("invalid option %s", param)
} }
if sParam[0]!="nodeid" { if sParam[0] != "nodeid" {
return fmt.Errorf("invalid option %s",param) return fmt.Errorf("invalid option %s", param)
} }
nodeId,err:= strconv.Atoi(sParam[1]) nodeId, err := strconv.Atoi(sParam[1])
if err != nil { if err != nil {
return fmt.Errorf("invalid option %s",param) return fmt.Errorf("invalid option %s", param)
} }
processId,err := getRunProcessPid(nodeId) processId, err := getRunProcessPid(nodeId)
if err != nil { if err != nil {
return err return err
} }
@@ -217,26 +217,26 @@ func stopNode(args interface{}) error {
return nil return nil
} }
func startNode(args interface{}) error{ func startNode(args interface{}) error {
//1.解析参数 //1.解析参数
param := args.(string) param := args.(string)
if param == "" { if param == "" {
return nil return nil
} }
sParam := strings.Split(param,"=") sParam := strings.Split(param, "=")
if len(sParam) != 2 { if len(sParam) != 2 {
return fmt.Errorf("invalid option %s",param) return fmt.Errorf("invalid option %s", param)
} }
if sParam[0]!="nodeid" { if sParam[0] != "nodeid" {
return fmt.Errorf("invalid option %s",param) return fmt.Errorf("invalid option %s", param)
} }
nodeId,err:= strconv.Atoi(sParam[1]) nodeId, err := strconv.Atoi(sParam[1])
if err != nil { if err != nil {
return fmt.Errorf("invalid option %s",param) return fmt.Errorf("invalid option %s", param)
} }
timer.StartTimer(10*time.Millisecond,1000000) timer.StartTimer(10*time.Millisecond, 1000000)
log.SRelease("Start running server.") log.SRelease("Start running server.")
//2.初始化node //2.初始化node
initNode(nodeId) initNode(nodeId)
@@ -253,7 +253,7 @@ func startNode(args interface{}) error{
//6.监听程序退出信号&性能报告 //6.监听程序退出信号&性能报告
bRun := true bRun := true
var pProfilerTicker *time.Ticker = &time.Ticker{} var pProfilerTicker *time.Ticker = &time.Ticker{}
if profilerInterval>0 { if profilerInterval > 0 {
pProfilerTicker = time.NewTicker(profilerInterval) pProfilerTicker = time.NewTicker(profilerInterval)
} }
for bRun { for bRun {
@@ -261,7 +261,7 @@ func startNode(args interface{}) error{
case <-sig: case <-sig:
log.SRelease("receipt stop signal.") log.SRelease("receipt stop signal.")
bRun = false bRun = false
case <- pProfilerTicker.C: case <-pProfilerTicker.C:
profiler.Report() profiler.Report()
} }
} }
@@ -274,11 +274,10 @@ func startNode(args interface{}) error{
return nil return nil
} }
func Setup(s ...service.IService) {
func Setup(s ...service.IService) { for _, sv := range s {
for _,sv := range s {
sv.OnSetup(sv) sv.OnSetup(sv)
preSetupService = append(preSetupService,sv) preSetupService = append(preSetupService, sv)
} }
} }
@@ -286,7 +285,7 @@ func GetService(serviceName string) service.IService {
return service.GetService(serviceName) return service.GetService(serviceName)
} }
func SetConfigDir(configDir string){ func SetConfigDir(configDir string) {
configDir = configDir configDir = configDir
cluster.SetConfigDir(configDir) cluster.SetConfigDir(configDir)
} }
@@ -295,58 +294,58 @@ func GetConfigDir() string {
return configDir return configDir
} }
func SetSysLog(strLevel string, pathname string, flag int){ func SetSysLog(strLevel string, pathname string, flag int) {
logs,_:= log.New(strLevel,pathname, "", flag,10) logs, _ := log.New(strLevel, pathname, "", flag, 10)
log.Export(logs) log.Export(logs)
} }
func OpenProfilerReport(interval time.Duration){ func OpenProfilerReport(interval time.Duration) {
profilerInterval = interval profilerInterval = interval
} }
func openConsole(args interface{}) error{ func openConsole(args interface{}) error {
if args == "" { if args == "" {
return nil return nil
} }
strOpen := strings.ToLower(strings.TrimSpace(args.(string))) strOpen := strings.ToLower(strings.TrimSpace(args.(string)))
if strOpen == "false" { if strOpen == "false" {
log.OpenConsole = false log.OpenConsole = false
}else if strOpen == "true" { } else if strOpen == "true" {
log.OpenConsole = true log.OpenConsole = true
}else{ } else {
return errors.New("Parameter console error!") return errors.New("Parameter console error!")
} }
return nil return nil
} }
func setLevel(args interface{}) error{ func setLevel(args interface{}) error {
if args==""{ if args == "" {
return nil return nil
} }
logLevel = strings.TrimSpace(args.(string)) logLevel = strings.TrimSpace(args.(string))
if logLevel!= "debug" && logLevel!="release"&& logLevel!="warning"&&logLevel!="error"&&logLevel!="fatal" { if logLevel != "debug" && logLevel != "release" && logLevel != "warning" && logLevel != "error" && logLevel != "fatal" {
return errors.New("unknown level: " + logLevel) return errors.New("unknown level: " + logLevel)
} }
return nil return nil
} }
func setLogPath(args interface{}) error{ func setLogPath(args interface{}) error {
if args == ""{ if args == "" {
return nil return nil
} }
logPath = strings.TrimSpace(args.(string)) logPath = strings.TrimSpace(args.(string))
dir, err := os.Stat(logPath) //这个文件夹不存在 dir, err := os.Stat(logPath) //这个文件夹不存在
if err == nil && dir.IsDir()==false { if err == nil && dir.IsDir() == false {
return errors.New("Not found dir "+logPath) return errors.New("Not found dir " + logPath)
} }
if err != nil { if err != nil {
err = os.Mkdir(logPath, os.ModePerm) err = os.Mkdir(logPath, os.ModePerm)
if err != nil { if err != nil {
return errors.New("Cannot create dir "+logPath) return errors.New("Cannot create dir " + logPath)
} }
} }
return nil return nil
} }

View File

@@ -4,7 +4,7 @@ import (
"bytes" "bytes"
"crypto/tls" "crypto/tls"
"fmt" "fmt"
"io/ioutil" "io"
"net" "net"
"net/http" "net/http"
"net/url" "net/url"
@@ -64,7 +64,7 @@ func (m *HttpClientModule) Init(maxpool int, proxyUrl string) {
Proxy: proxyFun, Proxy: proxyFun,
TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}, },
Timeout: 5 * time.Second, Timeout: 5 * time.Second,
} }
} }
@@ -103,7 +103,7 @@ func (m *HttpClientModule) Request(method string, url string, body []byte, heade
} }
defer rsp.Body.Close() defer rsp.Body.Close()
ret.Body, err = ioutil.ReadAll(rsp.Body) ret.Body, err = io.ReadAll(rsp.Body)
if err != nil { if err != nil {
ret.Err = err ret.Err = err
return ret return ret

View File

@@ -8,7 +8,6 @@ import (
"github.com/duanhf2012/origin/util/uuid" "github.com/duanhf2012/origin/util/uuid"
jsoniter "github.com/json-iterator/go" jsoniter "github.com/json-iterator/go"
"io" "io"
"io/ioutil"
"net/http" "net/http"
"os" "os"
"strings" "strings"
@@ -17,13 +16,13 @@ import (
var json = jsoniter.ConfigCompatibleWithStandardLibrary var json = jsoniter.ConfigCompatibleWithStandardLibrary
var DefaultReadTimeout time.Duration = time.Second*10 var DefaultReadTimeout time.Duration = time.Second * 10
var DefaultWriteTimeout time.Duration = time.Second*10 var DefaultWriteTimeout time.Duration = time.Second * 10
var DefaultProcessTimeout time.Duration = time.Second*10 var DefaultProcessTimeout time.Duration = time.Second * 10
//http redirect //http redirect
type HttpRedirectData struct { type HttpRedirectData struct {
Url string Url string
CookieList []*http.Cookie CookieList []*http.Cookie
} }
@@ -44,7 +43,7 @@ type routerMatchData struct {
} }
type routerServeFileData struct { type routerServeFileData struct {
matchUrl string matchUrl string
localPath string localPath string
method HTTP_METHOD method HTTP_METHOD
} }
@@ -56,44 +55,43 @@ type IHttpRouter interface {
SetServeFile(method HTTP_METHOD, urlpath string, dirname string) error SetServeFile(method HTTP_METHOD, urlpath string, dirname string) error
SetFormFileKey(formFileKey string) SetFormFileKey(formFileKey string)
GetFormFileKey()string GetFormFileKey() string
AddHttpFiltrate(FiltrateFun HttpFiltrate) bool AddHttpFiltrate(FiltrateFun HttpFiltrate) bool
} }
type HttpRouter struct { type HttpRouter struct {
pathRouter map[HTTP_METHOD] map[string] routerMatchData //url地址对应本service地址 pathRouter map[HTTP_METHOD]map[string]routerMatchData //url地址对应本service地址
serveFileData map[string] *routerServeFileData serveFileData map[string]*routerServeFileData
httpFiltrateList [] HttpFiltrate httpFiltrateList []HttpFiltrate
formFileKey string formFileKey string
} }
type HttpSession struct { type HttpSession struct {
httpRouter IHttpRouter httpRouter IHttpRouter
r *http.Request r *http.Request
w http.ResponseWriter w http.ResponseWriter
//parse result //parse result
mapParam map[string]string mapParam map[string]string
body []byte body []byte
//processor result //processor result
statusCode int statusCode int
msg []byte msg []byte
fileData *routerServeFileData fileData *routerServeFileData
redirectData *HttpRedirectData redirectData *HttpRedirectData
sessionDone chan *HttpSession sessionDone chan *HttpSession
} }
type HttpService struct { type HttpService struct {
service.Service service.Service
httpServer network.HttpServer httpServer network.HttpServer
postAliasUrl map[HTTP_METHOD] map[string]routerMatchData //url地址对应本service地址 postAliasUrl map[HTTP_METHOD]map[string]routerMatchData //url地址对应本service地址
httpRouter IHttpRouter httpRouter IHttpRouter
listenAddr string listenAddr string
corsHeader *CORSHeader corsHeader *CORSHeader
processTimeout time.Duration processTimeout time.Duration
} }
@@ -109,11 +107,11 @@ func (httpService *HttpService) AddFiltrate(FiltrateFun HttpFiltrate) bool {
func NewHttpHttpRouter() IHttpRouter { func NewHttpHttpRouter() IHttpRouter {
httpRouter := &HttpRouter{} httpRouter := &HttpRouter{}
httpRouter.pathRouter =map[HTTP_METHOD] map[string] routerMatchData{} httpRouter.pathRouter = map[HTTP_METHOD]map[string]routerMatchData{}
httpRouter.serveFileData = map[string] *routerServeFileData{} httpRouter.serveFileData = map[string]*routerServeFileData{}
httpRouter.formFileKey = "file" httpRouter.formFileKey = "file"
for i:=METHOD_NONE+1;i<METHOD_INVALID;i++{ for i := METHOD_NONE + 1; i < METHOD_INVALID; i++ {
httpRouter.pathRouter[i] = map[string] routerMatchData{} httpRouter.pathRouter[i] = map[string]routerMatchData{}
} }
return httpRouter return httpRouter
@@ -137,7 +135,7 @@ func (slf *HttpSession) Query(key string) (string, bool) {
return ret, ok return ret, ok
} }
func (slf *HttpSession) GetBody() []byte{ func (slf *HttpSession) GetBody() []byte {
return slf.body return slf.body
} }
@@ -145,19 +143,19 @@ func (slf *HttpSession) GetMethod() HTTP_METHOD {
return slf.getMethod(slf.r.Method) return slf.getMethod(slf.r.Method)
} }
func (slf *HttpSession) GetPath() string{ func (slf *HttpSession) GetPath() string {
return strings.Trim(slf.r.URL.Path,"/") return strings.Trim(slf.r.URL.Path, "/")
} }
func (slf *HttpSession) SetHeader(key, value string) { func (slf *HttpSession) SetHeader(key, value string) {
slf.w.Header().Set(key,value) slf.w.Header().Set(key, value)
} }
func (slf *HttpSession) AddHeader(key, value string) { func (slf *HttpSession) AddHeader(key, value string) {
slf.w.Header().Add(key,value) slf.w.Header().Add(key, value)
} }
func (slf *HttpSession) GetHeader(key string) string{ func (slf *HttpSession) GetHeader(key string) string {
return slf.r.Header.Get(key) return slf.r.Header.Get(key)
} }
@@ -165,7 +163,7 @@ func (slf *HttpSession) DelHeader(key string) {
slf.r.Header.Del(key) slf.r.Header.Del(key)
} }
func (slf *HttpSession) WriteStatusCode(statusCode int){ func (slf *HttpSession) WriteStatusCode(statusCode int) {
slf.statusCode = statusCode slf.statusCode = statusCode
} }
@@ -173,7 +171,7 @@ func (slf *HttpSession) Write(msg []byte) {
slf.msg = msg slf.msg = msg
} }
func (slf *HttpSession) WriteJsonDone(statusCode int,msgJson interface{}) error { func (slf *HttpSession) WriteJsonDone(statusCode int, msgJson interface{}) error {
msg, err := json.Marshal(msgJson) msg, err := json.Marshal(msgJson)
if err != nil { if err != nil {
return err return err
@@ -187,12 +185,12 @@ func (slf *HttpSession) WriteJsonDone(statusCode int,msgJson interface{}) error
func (slf *HttpSession) flush() { func (slf *HttpSession) flush() {
slf.w.WriteHeader(slf.statusCode) slf.w.WriteHeader(slf.statusCode)
if slf.msg!=nil { if slf.msg != nil {
slf.w.Write(slf.msg) slf.w.Write(slf.msg)
} }
} }
func (slf *HttpSession) Done(){ func (slf *HttpSession) Done() {
slf.sessionDone <- slf slf.sessionDone <- slf
} }
@@ -219,15 +217,15 @@ func (slf *HttpRouter) analysisRouterUrl(url string) (string, error) {
return strings.Trim(url, "/"), nil return strings.Trim(url, "/"), nil
} }
func (slf *HttpSession) Handle(){ func (slf *HttpSession) Handle() {
slf.httpRouter.Router(slf) slf.httpRouter.Router(slf)
} }
func (slf *HttpRouter) SetFormFileKey(formFileKey string){ func (slf *HttpRouter) SetFormFileKey(formFileKey string) {
slf.formFileKey = formFileKey slf.formFileKey = formFileKey
} }
func (slf *HttpRouter) GetFormFileKey()string{ func (slf *HttpRouter) GetFormFileKey() string {
return slf.formFileKey return slf.formFileKey
} }
@@ -239,19 +237,19 @@ func (slf *HttpRouter) POST(url string, handle HttpHandle) bool {
return slf.regRouter(METHOD_POST, url, handle) return slf.regRouter(METHOD_POST, url, handle)
} }
func (slf *HttpRouter) regRouter(method HTTP_METHOD, url string, handle HttpHandle) bool{ func (slf *HttpRouter) regRouter(method HTTP_METHOD, url string, handle HttpHandle) bool {
mapRouter,ok := slf.pathRouter[method] mapRouter, ok := slf.pathRouter[method]
if ok == false{ if ok == false {
return false return false
} }
mapRouter[strings.Trim(url,"/")] = routerMatchData{httpHandle:handle} mapRouter[strings.Trim(url, "/")] = routerMatchData{httpHandle: handle}
return true return true
} }
func (slf *HttpRouter) Router(session *HttpSession){ func (slf *HttpRouter) Router(session *HttpSession) {
if slf.httpFiltrateList!=nil { if slf.httpFiltrateList != nil {
for _,fun := range slf.httpFiltrateList{ for _, fun := range slf.httpFiltrateList {
if fun(session) == false { if fun(session) == false {
//session.done() //session.done()
return return
@@ -288,13 +286,13 @@ func (slf *HttpRouter) Router(session *HttpSession){
session.Done() session.Done()
} }
func (httpService *HttpService) HttpEventHandler(ev event.IEvent) { func (httpService *HttpService) HttpEventHandler(ev event.IEvent) {
ev.(*event.Event).Data.(*HttpSession).Handle() ev.(*event.Event).Data.(*HttpSession).Handle()
} }
func (httpService *HttpService) SetHttpRouter(httpRouter IHttpRouter,eventHandler event.IEventHandler) { func (httpService *HttpService) SetHttpRouter(httpRouter IHttpRouter, eventHandler event.IEventHandler) {
httpService.httpRouter = httpRouter httpService.httpRouter = httpRouter
httpService.RegEventReceiverFunc(event.Sys_Event_Http_Event,eventHandler, httpService.HttpEventHandler) httpService.RegEventReceiverFunc(event.Sys_Event_Http_Event, eventHandler, httpService.HttpEventHandler)
} }
func (slf *HttpRouter) SetServeFile(method HTTP_METHOD, urlpath string, dirname string) error { func (slf *HttpRouter) SetServeFile(method HTTP_METHOD, urlpath string, dirname string) error {
@@ -350,48 +348,48 @@ func (httpService *HttpService) OnInit() error {
return fmt.Errorf("%s service config is error!", httpService.GetName()) return fmt.Errorf("%s service config is error!", httpService.GetName())
} }
tcpCfg := iConfig.(map[string]interface{}) tcpCfg := iConfig.(map[string]interface{})
addr,ok := tcpCfg["ListenAddr"] addr, ok := tcpCfg["ListenAddr"]
if ok == false { if ok == false {
return fmt.Errorf("%s service config is error!", httpService.GetName()) return fmt.Errorf("%s service config is error!", httpService.GetName())
} }
var readTimeout time.Duration = DefaultReadTimeout var readTimeout time.Duration = DefaultReadTimeout
var writeTimeout time.Duration = DefaultWriteTimeout var writeTimeout time.Duration = DefaultWriteTimeout
if cfgRead,ok := tcpCfg["ReadTimeout"];ok == true { if cfgRead, ok := tcpCfg["ReadTimeout"]; ok == true {
readTimeout = time.Duration(cfgRead.(float64))*time.Millisecond readTimeout = time.Duration(cfgRead.(float64)) * time.Millisecond
} }
if cfgWrite,ok := tcpCfg["WriteTimeout"];ok == true { if cfgWrite, ok := tcpCfg["WriteTimeout"]; ok == true {
writeTimeout = time.Duration(cfgWrite.(float64))*time.Millisecond writeTimeout = time.Duration(cfgWrite.(float64)) * time.Millisecond
} }
httpService.processTimeout = DefaultProcessTimeout httpService.processTimeout = DefaultProcessTimeout
if cfgProcessTimeout,ok := tcpCfg["ProcessTimeout"];ok == true { if cfgProcessTimeout, ok := tcpCfg["ProcessTimeout"]; ok == true {
httpService.processTimeout = time.Duration(cfgProcessTimeout.(float64))*time.Millisecond httpService.processTimeout = time.Duration(cfgProcessTimeout.(float64)) * time.Millisecond
} }
httpService.httpServer.Init(addr.(string), httpService, readTimeout, writeTimeout) httpService.httpServer.Init(addr.(string), httpService, readTimeout, writeTimeout)
//Set CAFile //Set CAFile
caFileList,ok := tcpCfg["CAFile"] caFileList, ok := tcpCfg["CAFile"]
if ok == false { if ok == false {
return nil return nil
} }
iCaList := caFileList.([]interface{}) iCaList := caFileList.([]interface{})
var caFile [] network.CAFile var caFile []network.CAFile
for _,i := range iCaList { for _, i := range iCaList {
mapCAFile := i.(map[string]interface{}) mapCAFile := i.(map[string]interface{})
c,ok := mapCAFile["Certfile"] c, ok := mapCAFile["Certfile"]
if ok == false{ if ok == false {
continue continue
} }
k,ok := mapCAFile["Keyfile"] k, ok := mapCAFile["Keyfile"]
if ok == false{ if ok == false {
continue continue
} }
if c.(string)!="" && k.(string)!="" { if c.(string) != "" && k.(string) != "" {
caFile = append(caFile,network.CAFile{ caFile = append(caFile, network.CAFile{
CertFile: c.(string), CertFile: c.(string),
Keyfile: k.(string), Keyfile: k.(string),
}) })
} }
@@ -405,12 +403,12 @@ func (httpService *HttpService) SetAllowCORS(corsHeader *CORSHeader) {
httpService.corsHeader = corsHeader httpService.corsHeader = corsHeader
} }
func (httpService *HttpService) ProcessFile(session *HttpSession){ func (httpService *HttpService) ProcessFile(session *HttpSession) {
uPath := session.r.URL.Path uPath := session.r.URL.Path
idx := strings.Index(uPath, session.fileData.matchUrl) idx := strings.Index(uPath, session.fileData.matchUrl)
subPath := strings.Trim(uPath[idx+len(session.fileData.matchUrl):], "/") subPath := strings.Trim(uPath[idx+len(session.fileData.matchUrl):], "/")
destLocalPath := session.fileData.localPath + "/"+subPath destLocalPath := session.fileData.localPath + "/" + subPath
switch session.GetMethod() { switch session.GetMethod() {
case METHOD_GET: case METHOD_GET:
@@ -454,29 +452,29 @@ func (httpService *HttpService) ProcessFile(session *HttpSession){
defer localFd.Close() defer localFd.Close()
io.Copy(localFd, resourceFile) io.Copy(localFd, resourceFile)
session.WriteStatusCode(http.StatusOK) session.WriteStatusCode(http.StatusOK)
session.Write([]byte(uPath+"/"+fileName)) session.Write([]byte(uPath + "/" + fileName))
session.flush() session.flush()
} }
} }
func NewAllowCORSHeader() *CORSHeader{ func NewAllowCORSHeader() *CORSHeader {
header := &CORSHeader{} header := &CORSHeader{}
header.AllowCORSHeader = map[string][]string{} header.AllowCORSHeader = map[string][]string{}
header.AllowCORSHeader["Access-Control-Allow-Origin"] = []string{"*"} header.AllowCORSHeader["Access-Control-Allow-Origin"] = []string{"*"}
header.AllowCORSHeader["Access-Control-Allow-Methods"] =[]string{ "POST, GET, OPTIONS, PUT, DELETE"} header.AllowCORSHeader["Access-Control-Allow-Methods"] = []string{"POST, GET, OPTIONS, PUT, DELETE"}
header.AllowCORSHeader["Access-Control-Allow-Headers"] = []string{"Content-Type"} header.AllowCORSHeader["Access-Control-Allow-Headers"] = []string{"Content-Type"}
return header return header
} }
func (slf *CORSHeader) AddAllowHeader(key string,val string){ func (slf *CORSHeader) AddAllowHeader(key string, val string) {
slf.AllowCORSHeader["Access-Control-Allow-Headers"] = append(slf.AllowCORSHeader["Access-Control-Allow-Headers"],fmt.Sprintf("%s,%s",key,val)) slf.AllowCORSHeader["Access-Control-Allow-Headers"] = append(slf.AllowCORSHeader["Access-Control-Allow-Headers"], fmt.Sprintf("%s,%s", key, val))
} }
func (slf *CORSHeader) copyTo(header http.Header){ func (slf *CORSHeader) copyTo(header http.Header) {
for k,v := range slf.AllowCORSHeader{ for k, v := range slf.AllowCORSHeader {
for _,val := range v{ for _, val := range v {
header.Add(k,val) header.Add(k, val)
} }
} }
} }
@@ -491,12 +489,12 @@ func (httpService *HttpService) ServeHTTP(w http.ResponseWriter, r *http.Request
return return
} }
session := &HttpSession{sessionDone:make(chan *HttpSession,1),httpRouter:httpService.httpRouter,statusCode:http.StatusOK} session := &HttpSession{sessionDone: make(chan *HttpSession, 1), httpRouter: httpService.httpRouter, statusCode: http.StatusOK}
session.r = r session.r = r
session.w = w session.w = w
defer r.Body.Close() defer r.Body.Close()
body, err := ioutil.ReadAll(r.Body) body, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
session.WriteStatusCode(http.StatusGatewayTimeout) session.WriteStatusCode(http.StatusGatewayTimeout)
session.flush() session.flush()
@@ -504,19 +502,19 @@ func (httpService *HttpService) ServeHTTP(w http.ResponseWriter, r *http.Request
} }
session.body = body session.body = body
httpService.GetEventHandler().NotifyEvent(&event.Event{Type:event.Sys_Event_Http_Event,Data:session}) httpService.GetEventHandler().NotifyEvent(&event.Event{Type: event.Sys_Event_Http_Event, Data: session})
ticker := time.NewTicker(httpService.processTimeout) ticker := time.NewTicker(httpService.processTimeout)
select { select {
case <-ticker.C: case <-ticker.C:
session.WriteStatusCode(http.StatusGatewayTimeout) session.WriteStatusCode(http.StatusGatewayTimeout)
session.flush() session.flush()
break break
case <- session.sessionDone: case <-session.sessionDone:
if session.fileData!=nil { if session.fileData != nil {
httpService.ProcessFile(session) httpService.ProcessFile(session)
}else if session.redirectData!=nil { } else if session.redirectData != nil {
session.redirects() session.redirects()
}else{ } else {
session.flush() session.flush()
} }
} }