mirror of
https://github.com/duanhf2012/origin.git
synced 2026-02-03 22:45:13 +08:00
替换ioutil包为os/io包,它在1.16开始被弃用
This commit is contained in:
@@ -5,7 +5,7 @@ import (
|
||||
"github.com/duanhf2012/origin/log"
|
||||
"github.com/duanhf2012/origin/rpc"
|
||||
jsoniter "github.com/json-iterator/go"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -18,7 +18,7 @@ type NodeInfoList struct {
|
||||
|
||||
func (cls *Cluster) ReadClusterConfig(filepath string) (*NodeInfoList, error) {
|
||||
c := &NodeInfoList{}
|
||||
d, err := ioutil.ReadFile(filepath)
|
||||
d, err := os.ReadFile(filepath)
|
||||
if err != nil {
|
||||
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) {
|
||||
c := map[string]interface{}{}
|
||||
//读取配置
|
||||
d, err := ioutil.ReadFile(filepath)
|
||||
d, err := os.ReadFile(filepath)
|
||||
if err != nil {
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
@@ -69,7 +69,7 @@ func (cls *Cluster) readLocalClusterConfig(nodeId int) ([]NodeInfo, []NodeInfo,
|
||||
var nodeInfoList []NodeInfo
|
||||
var masterDiscoverNodeList []NodeInfo
|
||||
clusterCfgPath := strings.TrimRight(configDir, "/") + "/cluster"
|
||||
fileInfoList, err := ioutil.ReadDir(clusterCfgPath)
|
||||
fileInfoList, err := os.ReadDir(clusterCfgPath)
|
||||
if err != nil {
|
||||
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 {
|
||||
clusterCfgPath := strings.TrimRight(configDir, "/") + "/cluster"
|
||||
fileInfoList, err := ioutil.ReadDir(clusterCfgPath)
|
||||
fileInfoList, err := os.ReadDir(clusterCfgPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Read dir %s is fail :%+v", clusterCfgPath, err)
|
||||
}
|
||||
|
||||
149
node/node.go
149
node/node.go
@@ -8,9 +8,9 @@ import (
|
||||
"github.com/duanhf2012/origin/log"
|
||||
"github.com/duanhf2012/origin/profiler"
|
||||
"github.com/duanhf2012/origin/service"
|
||||
"github.com/duanhf2012/origin/util/timer"
|
||||
"github.com/duanhf2012/origin/util/buildtime"
|
||||
"io/ioutil"
|
||||
"github.com/duanhf2012/origin/util/timer"
|
||||
"io"
|
||||
slog "log"
|
||||
"net/http"
|
||||
_ "net/http/pprof"
|
||||
@@ -34,30 +34,30 @@ var logPath string
|
||||
|
||||
func init() {
|
||||
|
||||
closeSig = make(chan bool,1)
|
||||
closeSig = make(chan bool, 1)
|
||||
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.RegisterCommandString("name","","<-name nodeName> Node's name.",setName)
|
||||
console.RegisterCommandString("start","","<-start nodeid=nodeid> Run originserver.",startNode)
|
||||
console.RegisterCommandString("stop","","<-stop nodeid=nodeid> Stop originserver process.",stopNode)
|
||||
console.RegisterCommandString("config","","<-config path> Configuration file path.",setConfigPath)
|
||||
console.RegisterCommandBool("help", false, "<-help> This help.", usage)
|
||||
console.RegisterCommandString("name", "", "<-name nodeName> Node's name.", setName)
|
||||
console.RegisterCommandString("start", "", "<-start nodeid=nodeid> Run originserver.", startNode)
|
||||
console.RegisterCommandString("stop", "", "<-stop nodeid=nodeid> Stop originserver process.", stopNode)
|
||||
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("loglevel", "debug", "<-loglevel debug|release|warning|error|fatal> Set loglevel.", setLevel)
|
||||
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)
|
||||
if ret == false {
|
||||
return nil
|
||||
}
|
||||
|
||||
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())
|
||||
}else{
|
||||
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())
|
||||
} else {
|
||||
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 {
|
||||
listenAddr := val.(string)
|
||||
if listenAddr==""{
|
||||
if listenAddr == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
go func(){
|
||||
go func() {
|
||||
err := http.ListenAndServe(listenAddr, nil)
|
||||
if err != nil {
|
||||
panic(fmt.Errorf("%+v",err))
|
||||
panic(fmt.Errorf("%+v", err))
|
||||
}
|
||||
}()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func setConfigPath(val interface{}) error{
|
||||
func setConfigPath(val interface{}) error {
|
||||
configPath := val.(string)
|
||||
if configPath==""{
|
||||
if configPath == "" {
|
||||
return nil
|
||||
}
|
||||
_, err := os.Stat(configPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Cannot find file path %s",configPath)
|
||||
return fmt.Errorf("Cannot find file path %s", configPath)
|
||||
}
|
||||
|
||||
cluster.SetConfigDir(configPath)
|
||||
@@ -100,16 +100,16 @@ func setConfigPath(val interface{}) error{
|
||||
return nil
|
||||
}
|
||||
|
||||
func getRunProcessPid(nodeId int) (int,error) {
|
||||
f, err := os.OpenFile(fmt.Sprintf("%s_%d.pid",os.Args[0],nodeId), os.O_RDONLY, 0600)
|
||||
func getRunProcessPid(nodeId int) (int, error) {
|
||||
f, err := os.OpenFile(fmt.Sprintf("%s_%d.pid", os.Args[0], nodeId), os.O_RDONLY, 0600)
|
||||
defer f.Close()
|
||||
if err!= nil {
|
||||
return 0,err
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
pidByte,errs := ioutil.ReadAll(f)
|
||||
if errs!=nil {
|
||||
return 0,errs
|
||||
pidByte, errs := io.ReadAll(f)
|
||||
if errs != nil {
|
||||
return 0, errs
|
||||
}
|
||||
|
||||
return strconv.Atoi(string(pidByte))
|
||||
@@ -117,13 +117,13 @@ func getRunProcessPid(nodeId int) (int,error) {
|
||||
|
||||
func writeProcessPid(nodeId int) {
|
||||
//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()
|
||||
if err != nil {
|
||||
fmt.Println(err.Error())
|
||||
os.Exit(-1)
|
||||
} else {
|
||||
_,err=f.Write([]byte(fmt.Sprintf("%d",os.Getpid())))
|
||||
_, err = f.Write([]byte(fmt.Sprintf("%d", os.Getpid())))
|
||||
if err != nil {
|
||||
fmt.Println(err.Error())
|
||||
os.Exit(-1)
|
||||
@@ -135,28 +135,28 @@ func GetNodeId() int {
|
||||
return nodeId
|
||||
}
|
||||
|
||||
func initNode(id int){
|
||||
func initNode(id int) {
|
||||
//1.初始化集群
|
||||
nodeId = id
|
||||
err := cluster.GetCluster().Init(GetNodeId(),Setup)
|
||||
err := cluster.GetCluster().Init(GetNodeId(), Setup)
|
||||
if err != nil {
|
||||
log.SFatal("read system config is error ",err.Error())
|
||||
log.SFatal("read system config is error ", err.Error())
|
||||
}
|
||||
|
||||
err = initLog()
|
||||
if err != nil{
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
//2.setup service
|
||||
for _,s := range preSetupService {
|
||||
for _, s := range preSetupService {
|
||||
//是否配置的service
|
||||
if cluster.GetCluster().IsConfigService(s.GetName()) == false {
|
||||
continue
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
@@ -165,14 +165,14 @@ func initNode(id int){
|
||||
service.Init(closeSig)
|
||||
}
|
||||
|
||||
func initLog() error{
|
||||
if logPath == ""{
|
||||
func initLog() error {
|
||||
if logPath == "" {
|
||||
setLogPath("./log")
|
||||
}
|
||||
|
||||
localnodeinfo := cluster.GetCluster().GetLocalNodeInfo()
|
||||
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 {
|
||||
fmt.Printf("cannot create log file!\n")
|
||||
return err
|
||||
@@ -183,8 +183,8 @@ func initLog() error{
|
||||
|
||||
func Start() {
|
||||
err := console.Run(os.Args)
|
||||
if err!=nil {
|
||||
fmt.Printf("%+v\n",err)
|
||||
if err != nil {
|
||||
fmt.Printf("%+v\n", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -196,19 +196,19 @@ func stopNode(args interface{}) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
sParam := strings.Split(param,"=")
|
||||
sParam := strings.Split(param, "=")
|
||||
if len(sParam) != 2 {
|
||||
return fmt.Errorf("invalid option %s",param)
|
||||
return fmt.Errorf("invalid option %s", param)
|
||||
}
|
||||
if sParam[0]!="nodeid" {
|
||||
return fmt.Errorf("invalid option %s",param)
|
||||
if sParam[0] != "nodeid" {
|
||||
return fmt.Errorf("invalid option %s", param)
|
||||
}
|
||||
nodeId,err:= strconv.Atoi(sParam[1])
|
||||
nodeId, err := strconv.Atoi(sParam[1])
|
||||
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 {
|
||||
return err
|
||||
}
|
||||
@@ -217,26 +217,26 @@ func stopNode(args interface{}) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func startNode(args interface{}) error{
|
||||
func startNode(args interface{}) error {
|
||||
//1.解析参数
|
||||
param := args.(string)
|
||||
if param == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
sParam := strings.Split(param,"=")
|
||||
sParam := strings.Split(param, "=")
|
||||
if len(sParam) != 2 {
|
||||
return fmt.Errorf("invalid option %s",param)
|
||||
return fmt.Errorf("invalid option %s", param)
|
||||
}
|
||||
if sParam[0]!="nodeid" {
|
||||
return fmt.Errorf("invalid option %s",param)
|
||||
if sParam[0] != "nodeid" {
|
||||
return fmt.Errorf("invalid option %s", param)
|
||||
}
|
||||
nodeId,err:= strconv.Atoi(sParam[1])
|
||||
nodeId, err := strconv.Atoi(sParam[1])
|
||||
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.")
|
||||
//2.初始化node
|
||||
initNode(nodeId)
|
||||
@@ -253,7 +253,7 @@ func startNode(args interface{}) error{
|
||||
//6.监听程序退出信号&性能报告
|
||||
bRun := true
|
||||
var pProfilerTicker *time.Ticker = &time.Ticker{}
|
||||
if profilerInterval>0 {
|
||||
if profilerInterval > 0 {
|
||||
pProfilerTicker = time.NewTicker(profilerInterval)
|
||||
}
|
||||
for bRun {
|
||||
@@ -261,7 +261,7 @@ func startNode(args interface{}) error{
|
||||
case <-sig:
|
||||
log.SRelease("receipt stop signal.")
|
||||
bRun = false
|
||||
case <- pProfilerTicker.C:
|
||||
case <-pProfilerTicker.C:
|
||||
profiler.Report()
|
||||
}
|
||||
}
|
||||
@@ -274,11 +274,10 @@ func startNode(args interface{}) error{
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
func Setup(s ...service.IService) {
|
||||
for _,sv := range s {
|
||||
for _, sv := range s {
|
||||
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)
|
||||
}
|
||||
|
||||
func SetConfigDir(configDir string){
|
||||
func SetConfigDir(configDir string) {
|
||||
configDir = configDir
|
||||
cluster.SetConfigDir(configDir)
|
||||
}
|
||||
@@ -295,56 +294,56 @@ func GetConfigDir() string {
|
||||
return configDir
|
||||
}
|
||||
|
||||
func SetSysLog(strLevel string, pathname string, flag int){
|
||||
logs,_:= log.New(strLevel,pathname, "", flag,10)
|
||||
func SetSysLog(strLevel string, pathname string, flag int) {
|
||||
logs, _ := log.New(strLevel, pathname, "", flag, 10)
|
||||
log.Export(logs)
|
||||
}
|
||||
|
||||
func OpenProfilerReport(interval time.Duration){
|
||||
func OpenProfilerReport(interval time.Duration) {
|
||||
profilerInterval = interval
|
||||
}
|
||||
|
||||
func openConsole(args interface{}) error{
|
||||
func openConsole(args interface{}) error {
|
||||
if args == "" {
|
||||
return nil
|
||||
}
|
||||
strOpen := strings.ToLower(strings.TrimSpace(args.(string)))
|
||||
if strOpen == "false" {
|
||||
log.OpenConsole = false
|
||||
}else if strOpen == "true" {
|
||||
} else if strOpen == "true" {
|
||||
log.OpenConsole = true
|
||||
}else{
|
||||
} else {
|
||||
return errors.New("Parameter console error!")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func setLevel(args interface{}) error{
|
||||
if args==""{
|
||||
func setLevel(args interface{}) error {
|
||||
if args == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
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 nil
|
||||
}
|
||||
|
||||
func setLogPath(args interface{}) error{
|
||||
if args == ""{
|
||||
func setLogPath(args interface{}) error {
|
||||
if args == "" {
|
||||
return nil
|
||||
}
|
||||
logPath = strings.TrimSpace(args.(string))
|
||||
dir, err := os.Stat(logPath) //这个文件夹不存在
|
||||
if err == nil && dir.IsDir()==false {
|
||||
return errors.New("Not found dir "+logPath)
|
||||
if err == nil && dir.IsDir() == false {
|
||||
return errors.New("Not found dir " + logPath)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
err = os.Mkdir(logPath, os.ModePerm)
|
||||
if err != nil {
|
||||
return errors.New("Cannot create dir "+logPath)
|
||||
return errors.New("Cannot create dir " + logPath)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"bytes"
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
@@ -103,7 +103,7 @@ func (m *HttpClientModule) Request(method string, url string, body []byte, heade
|
||||
}
|
||||
defer rsp.Body.Close()
|
||||
|
||||
ret.Body, err = ioutil.ReadAll(rsp.Body)
|
||||
ret.Body, err = io.ReadAll(rsp.Body)
|
||||
if err != nil {
|
||||
ret.Err = err
|
||||
return ret
|
||||
|
||||
@@ -8,7 +8,6 @@ import (
|
||||
"github.com/duanhf2012/origin/util/uuid"
|
||||
jsoniter "github.com/json-iterator/go"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
@@ -17,9 +16,9 @@ import (
|
||||
|
||||
var json = jsoniter.ConfigCompatibleWithStandardLibrary
|
||||
|
||||
var DefaultReadTimeout time.Duration = time.Second*10
|
||||
var DefaultWriteTimeout time.Duration = time.Second*10
|
||||
var DefaultProcessTimeout time.Duration = time.Second*10
|
||||
var DefaultReadTimeout time.Duration = time.Second * 10
|
||||
var DefaultWriteTimeout time.Duration = time.Second * 10
|
||||
var DefaultProcessTimeout time.Duration = time.Second * 10
|
||||
|
||||
//http redirect
|
||||
type HttpRedirectData struct {
|
||||
@@ -56,14 +55,14 @@ type IHttpRouter interface {
|
||||
|
||||
SetServeFile(method HTTP_METHOD, urlpath string, dirname string) error
|
||||
SetFormFileKey(formFileKey string)
|
||||
GetFormFileKey()string
|
||||
GetFormFileKey() string
|
||||
AddHttpFiltrate(FiltrateFun HttpFiltrate) bool
|
||||
}
|
||||
|
||||
type HttpRouter struct {
|
||||
pathRouter map[HTTP_METHOD] map[string] routerMatchData //url地址,对应本service地址
|
||||
serveFileData map[string] *routerServeFileData
|
||||
httpFiltrateList [] HttpFiltrate
|
||||
pathRouter map[HTTP_METHOD]map[string]routerMatchData //url地址,对应本service地址
|
||||
serveFileData map[string]*routerServeFileData
|
||||
httpFiltrateList []HttpFiltrate
|
||||
|
||||
formFileKey string
|
||||
}
|
||||
@@ -85,12 +84,11 @@ type HttpSession struct {
|
||||
sessionDone chan *HttpSession
|
||||
}
|
||||
|
||||
|
||||
type HttpService struct {
|
||||
service.Service
|
||||
|
||||
httpServer network.HttpServer
|
||||
postAliasUrl map[HTTP_METHOD] map[string]routerMatchData //url地址,对应本service地址
|
||||
postAliasUrl map[HTTP_METHOD]map[string]routerMatchData //url地址,对应本service地址
|
||||
httpRouter IHttpRouter
|
||||
listenAddr string
|
||||
corsHeader *CORSHeader
|
||||
@@ -109,11 +107,11 @@ func (httpService *HttpService) AddFiltrate(FiltrateFun HttpFiltrate) bool {
|
||||
|
||||
func NewHttpHttpRouter() IHttpRouter {
|
||||
httpRouter := &HttpRouter{}
|
||||
httpRouter.pathRouter =map[HTTP_METHOD] map[string] routerMatchData{}
|
||||
httpRouter.serveFileData = map[string] *routerServeFileData{}
|
||||
httpRouter.pathRouter = map[HTTP_METHOD]map[string]routerMatchData{}
|
||||
httpRouter.serveFileData = map[string]*routerServeFileData{}
|
||||
httpRouter.formFileKey = "file"
|
||||
for i:=METHOD_NONE+1;i<METHOD_INVALID;i++{
|
||||
httpRouter.pathRouter[i] = map[string] routerMatchData{}
|
||||
for i := METHOD_NONE + 1; i < METHOD_INVALID; i++ {
|
||||
httpRouter.pathRouter[i] = map[string]routerMatchData{}
|
||||
}
|
||||
|
||||
return httpRouter
|
||||
@@ -137,7 +135,7 @@ func (slf *HttpSession) Query(key string) (string, bool) {
|
||||
return ret, ok
|
||||
}
|
||||
|
||||
func (slf *HttpSession) GetBody() []byte{
|
||||
func (slf *HttpSession) GetBody() []byte {
|
||||
return slf.body
|
||||
}
|
||||
|
||||
@@ -145,19 +143,19 @@ func (slf *HttpSession) GetMethod() HTTP_METHOD {
|
||||
return slf.getMethod(slf.r.Method)
|
||||
}
|
||||
|
||||
func (slf *HttpSession) GetPath() string{
|
||||
return strings.Trim(slf.r.URL.Path,"/")
|
||||
func (slf *HttpSession) GetPath() string {
|
||||
return strings.Trim(slf.r.URL.Path, "/")
|
||||
}
|
||||
|
||||
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) {
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -165,7 +163,7 @@ func (slf *HttpSession) DelHeader(key string) {
|
||||
slf.r.Header.Del(key)
|
||||
}
|
||||
|
||||
func (slf *HttpSession) WriteStatusCode(statusCode int){
|
||||
func (slf *HttpSession) WriteStatusCode(statusCode int) {
|
||||
slf.statusCode = statusCode
|
||||
}
|
||||
|
||||
@@ -173,7 +171,7 @@ func (slf *HttpSession) Write(msg []byte) {
|
||||
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)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -187,12 +185,12 @@ func (slf *HttpSession) WriteJsonDone(statusCode int,msgJson interface{}) error
|
||||
|
||||
func (slf *HttpSession) flush() {
|
||||
slf.w.WriteHeader(slf.statusCode)
|
||||
if slf.msg!=nil {
|
||||
if slf.msg != nil {
|
||||
slf.w.Write(slf.msg)
|
||||
}
|
||||
}
|
||||
|
||||
func (slf *HttpSession) Done(){
|
||||
func (slf *HttpSession) Done() {
|
||||
slf.sessionDone <- slf
|
||||
}
|
||||
|
||||
@@ -219,15 +217,15 @@ func (slf *HttpRouter) analysisRouterUrl(url string) (string, error) {
|
||||
return strings.Trim(url, "/"), nil
|
||||
}
|
||||
|
||||
func (slf *HttpSession) Handle(){
|
||||
func (slf *HttpSession) Handle() {
|
||||
slf.httpRouter.Router(slf)
|
||||
}
|
||||
|
||||
func (slf *HttpRouter) SetFormFileKey(formFileKey string){
|
||||
func (slf *HttpRouter) SetFormFileKey(formFileKey string) {
|
||||
slf.formFileKey = formFileKey
|
||||
}
|
||||
|
||||
func (slf *HttpRouter) GetFormFileKey()string{
|
||||
func (slf *HttpRouter) GetFormFileKey() string {
|
||||
return slf.formFileKey
|
||||
}
|
||||
|
||||
@@ -239,19 +237,19 @@ func (slf *HttpRouter) POST(url string, handle HttpHandle) bool {
|
||||
return slf.regRouter(METHOD_POST, url, handle)
|
||||
}
|
||||
|
||||
func (slf *HttpRouter) regRouter(method HTTP_METHOD, url string, handle HttpHandle) bool{
|
||||
mapRouter,ok := slf.pathRouter[method]
|
||||
if ok == false{
|
||||
func (slf *HttpRouter) regRouter(method HTTP_METHOD, url string, handle HttpHandle) bool {
|
||||
mapRouter, ok := slf.pathRouter[method]
|
||||
if ok == false {
|
||||
return false
|
||||
}
|
||||
|
||||
mapRouter[strings.Trim(url,"/")] = routerMatchData{httpHandle:handle}
|
||||
mapRouter[strings.Trim(url, "/")] = routerMatchData{httpHandle: handle}
|
||||
return true
|
||||
}
|
||||
|
||||
func (slf *HttpRouter) Router(session *HttpSession){
|
||||
if slf.httpFiltrateList!=nil {
|
||||
for _,fun := range slf.httpFiltrateList{
|
||||
func (slf *HttpRouter) Router(session *HttpSession) {
|
||||
if slf.httpFiltrateList != nil {
|
||||
for _, fun := range slf.httpFiltrateList {
|
||||
if fun(session) == false {
|
||||
//session.done()
|
||||
return
|
||||
@@ -292,9 +290,9 @@ func (httpService *HttpService) HttpEventHandler(ev event.IEvent) {
|
||||
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.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 {
|
||||
@@ -350,47 +348,47 @@ func (httpService *HttpService) OnInit() error {
|
||||
return fmt.Errorf("%s service config is error!", httpService.GetName())
|
||||
}
|
||||
tcpCfg := iConfig.(map[string]interface{})
|
||||
addr,ok := tcpCfg["ListenAddr"]
|
||||
addr, ok := tcpCfg["ListenAddr"]
|
||||
if ok == false {
|
||||
return fmt.Errorf("%s service config is error!", httpService.GetName())
|
||||
}
|
||||
var readTimeout time.Duration = DefaultReadTimeout
|
||||
var writeTimeout time.Duration = DefaultWriteTimeout
|
||||
|
||||
if cfgRead,ok := tcpCfg["ReadTimeout"];ok == true {
|
||||
readTimeout = time.Duration(cfgRead.(float64))*time.Millisecond
|
||||
if cfgRead, ok := tcpCfg["ReadTimeout"]; ok == true {
|
||||
readTimeout = time.Duration(cfgRead.(float64)) * time.Millisecond
|
||||
}
|
||||
|
||||
if cfgWrite,ok := tcpCfg["WriteTimeout"];ok == true {
|
||||
writeTimeout = time.Duration(cfgWrite.(float64))*time.Millisecond
|
||||
if cfgWrite, ok := tcpCfg["WriteTimeout"]; ok == true {
|
||||
writeTimeout = time.Duration(cfgWrite.(float64)) * time.Millisecond
|
||||
}
|
||||
|
||||
httpService.processTimeout = DefaultProcessTimeout
|
||||
if cfgProcessTimeout,ok := tcpCfg["ProcessTimeout"];ok == true {
|
||||
httpService.processTimeout = time.Duration(cfgProcessTimeout.(float64))*time.Millisecond
|
||||
if cfgProcessTimeout, ok := tcpCfg["ProcessTimeout"]; ok == true {
|
||||
httpService.processTimeout = time.Duration(cfgProcessTimeout.(float64)) * time.Millisecond
|
||||
}
|
||||
|
||||
httpService.httpServer.Init(addr.(string), httpService, readTimeout, writeTimeout)
|
||||
//Set CAFile
|
||||
caFileList,ok := tcpCfg["CAFile"]
|
||||
caFileList, ok := tcpCfg["CAFile"]
|
||||
if ok == false {
|
||||
return nil
|
||||
}
|
||||
iCaList := caFileList.([]interface{})
|
||||
var caFile [] network.CAFile
|
||||
for _,i := range iCaList {
|
||||
var caFile []network.CAFile
|
||||
for _, i := range iCaList {
|
||||
mapCAFile := i.(map[string]interface{})
|
||||
c,ok := mapCAFile["Certfile"]
|
||||
if ok == false{
|
||||
c, ok := mapCAFile["Certfile"]
|
||||
if ok == false {
|
||||
continue
|
||||
}
|
||||
k,ok := mapCAFile["Keyfile"]
|
||||
if ok == false{
|
||||
k, ok := mapCAFile["Keyfile"]
|
||||
if ok == false {
|
||||
continue
|
||||
}
|
||||
|
||||
if c.(string)!="" && k.(string)!="" {
|
||||
caFile = append(caFile,network.CAFile{
|
||||
if c.(string) != "" && k.(string) != "" {
|
||||
caFile = append(caFile, network.CAFile{
|
||||
CertFile: c.(string),
|
||||
Keyfile: k.(string),
|
||||
})
|
||||
@@ -405,12 +403,12 @@ func (httpService *HttpService) SetAllowCORS(corsHeader *CORSHeader) {
|
||||
httpService.corsHeader = corsHeader
|
||||
}
|
||||
|
||||
func (httpService *HttpService) ProcessFile(session *HttpSession){
|
||||
func (httpService *HttpService) ProcessFile(session *HttpSession) {
|
||||
uPath := session.r.URL.Path
|
||||
idx := strings.Index(uPath, 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() {
|
||||
case METHOD_GET:
|
||||
@@ -454,29 +452,29 @@ func (httpService *HttpService) ProcessFile(session *HttpSession){
|
||||
defer localFd.Close()
|
||||
io.Copy(localFd, resourceFile)
|
||||
session.WriteStatusCode(http.StatusOK)
|
||||
session.Write([]byte(uPath+"/"+fileName))
|
||||
session.Write([]byte(uPath + "/" + fileName))
|
||||
session.flush()
|
||||
}
|
||||
}
|
||||
|
||||
func NewAllowCORSHeader() *CORSHeader{
|
||||
func NewAllowCORSHeader() *CORSHeader {
|
||||
header := &CORSHeader{}
|
||||
header.AllowCORSHeader = map[string][]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"}
|
||||
|
||||
return header
|
||||
}
|
||||
|
||||
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))
|
||||
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))
|
||||
}
|
||||
|
||||
func (slf *CORSHeader) copyTo(header http.Header){
|
||||
for k,v := range slf.AllowCORSHeader{
|
||||
for _,val := range v{
|
||||
header.Add(k,val)
|
||||
func (slf *CORSHeader) copyTo(header http.Header) {
|
||||
for k, v := range slf.AllowCORSHeader {
|
||||
for _, val := range v {
|
||||
header.Add(k, val)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -491,12 +489,12 @@ func (httpService *HttpService) ServeHTTP(w http.ResponseWriter, r *http.Request
|
||||
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.w = w
|
||||
|
||||
defer r.Body.Close()
|
||||
body, err := ioutil.ReadAll(r.Body)
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
session.WriteStatusCode(http.StatusGatewayTimeout)
|
||||
session.flush()
|
||||
@@ -504,19 +502,19 @@ func (httpService *HttpService) ServeHTTP(w http.ResponseWriter, r *http.Request
|
||||
}
|
||||
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)
|
||||
select {
|
||||
case <-ticker.C:
|
||||
session.WriteStatusCode(http.StatusGatewayTimeout)
|
||||
session.flush()
|
||||
break
|
||||
case <- session.sessionDone:
|
||||
if session.fileData!=nil {
|
||||
case <-session.sessionDone:
|
||||
if session.fileData != nil {
|
||||
httpService.ProcessFile(session)
|
||||
}else if session.redirectData!=nil {
|
||||
} else if session.redirectData != nil {
|
||||
session.redirects()
|
||||
}else{
|
||||
} else {
|
||||
session.flush()
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user