abango.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. package abango
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "log"
  6. "os"
  7. "strings"
  8. "time"
  9. "sync"
  10. _ "github.com/go-sql-driver/mysql"
  11. "github.com/go-xorm/xorm"
  12. e "github.com/dabory/abango-rest/etc"
  13. )
  14. // type EnvConf struct { //Kangan only
  15. // AppName string
  16. // HttpProtocol string
  17. // HttpAddr string
  18. // HttpPort string
  19. // SiteName string
  20. // DbType string
  21. // DbHost string
  22. // DbUser string
  23. // DbPassword string
  24. // DbPort string
  25. // DbName string
  26. // DbPrefix string
  27. // DbTimezone string
  28. // DbStr string
  29. // }
  30. type RunConf struct {
  31. RunMode string
  32. DevPrefix string
  33. ProdPrefix string
  34. ConfPostFix string
  35. }
  36. // type BaseReceiver struct {
  37. // GateToken string
  38. // }
  39. func init() {
  40. // e.OkLog("Abango Initialized")
  41. }
  42. func RunServicePoint(RestHandler func(ask *AbangoAsk)) {
  43. var wg sync.WaitGroup
  44. e.AokLog("Abango Clustered Framework Started !")
  45. if XConfig["XDBOn"] == "Yes" { // 필요없어진 건 같으니까 2024년에 지울것.
  46. MyLinkXDB()
  47. }
  48. if XConfig["CrystalDBOn"] == "Yes" { // 필요없어진 건 같으니까 2024년에 지울것.
  49. MyLinkCrystalDB()
  50. }
  51. if XConfig["IsQryFromQDB"] == "Yes" {
  52. QDBOn = true
  53. }
  54. if XConfig["KafkaOn"] == "Yes" {
  55. // wg.Add(1)
  56. // go func() {
  57. // KafkaSvcStandBy(KafkaHandler)
  58. // wg.Done()
  59. // }()
  60. }
  61. if XConfig["gRpcOn"] == "Yes" {
  62. // e.AokLog("gRpc API StandBy !")
  63. // wg.Add(1)
  64. // go func() {
  65. // // GrpcSvcStandBy(GrpcHandler)
  66. // wg.Done()
  67. // }()
  68. }
  69. if XConfig["RestOn"] == "Yes" {
  70. // e.AokLog("RESTful API StandBy !")
  71. wg.Add(1)
  72. go func() {
  73. RestSvcStandBy(RestHandler)
  74. wg.Done()
  75. }()
  76. }
  77. wg.Wait()
  78. }
  79. func RunRouterPostNormal(askuri string, body string) (string, string, string) {
  80. if err := GetXConfig(); err == nil {
  81. e.InitLog(XConfig["LogFilePath"], XConfig["ShowLogStdout"])
  82. log.Print("============ RunEndRequest Begins ==============")
  83. apiMethod := "POST"
  84. askBytes := []byte(body)
  85. restUri := XConfig["RestConnect"] + askuri
  86. if askuri == "upload-file" {
  87. if retBytes, retstaBytes, err := e.UploadFileResponse(apiMethod, restUri, askBytes); err == nil {
  88. var out bytes.Buffer
  89. err := json.Indent(&out, retBytes, "", " ")
  90. if err == nil {
  91. return out.String(), string(retstaBytes), ""
  92. } else {
  93. return string(retBytes), string(retstaBytes), ""
  94. }
  95. } else {
  96. return err.Error(), string(retstaBytes), ""
  97. }
  98. } else {
  99. if retBytes, retstaBytes, err := e.GetHttpResponse(apiMethod, restUri, askBytes); err == nil {
  100. var out bytes.Buffer
  101. err := json.Indent(&out, retBytes, "", " ")
  102. if err == nil {
  103. return out.String(), string(retstaBytes), ""
  104. } else {
  105. return string(retBytes), string(retstaBytes), ""
  106. }
  107. } else {
  108. return err.Error(), string(retstaBytes), ""
  109. }
  110. }
  111. } else {
  112. return "", "", e.MyErr("XCVZDSFGQWERDZ-Unable to get GetXConfig()", nil, true).Error()
  113. }
  114. // return "", "", "asfklsjljfad-Reached to end of RunEndRequest !"
  115. }
  116. func RunEndRequest(params string, body string) string {
  117. if err := GetXConfig(); err == nil {
  118. e.InitLog(XConfig["LogFilePath"], XConfig["ShowLogStdout"])
  119. log.Print("============ RunEndRequest Begins ==============")
  120. askfile := e.GetAskName()
  121. arrask := strings.Split(askfile, "@") // login@post 앞의 문자를 askname으로 설정
  122. askname := arrask[0]
  123. jsonsend := XConfig["JsonSendDir"] + askname + ".json"
  124. var err error
  125. if body, err = e.FileToStr(jsonsend); err != nil {
  126. return e.MyErr("WERZDSVCZSRE-JsonSendFile Not Found: ", err, true).Error()
  127. }
  128. if XConfig["ApiType"] == "Kafka" {
  129. // return RunRequest(KafkaRequest, &params, &body)
  130. } else if XConfig["ApiType"] == "gRpc" {
  131. // return RunRequest(GrpcRequest, &params, &body)
  132. } else if XConfig["ApiType"] == "Rest" {
  133. return RunRequest(RestRequest, &params, &body)
  134. } else {
  135. return e.MyErr("QREWFGARTEGF-Wrong ApiType in RunEndRequest()", nil, true).Error()
  136. }
  137. } else {
  138. return e.MyErr("XCVZDSFGQWERDZ-Unable to get GetXConfig()", nil, true).Error()
  139. }
  140. return "Reached to end of RunEndRequest !"
  141. }
  142. func RunRequest(MsgHandler func(v *AbangoAsk) (string, string, error), params *string, body *string) string {
  143. var v AbangoAsk
  144. v.UniqueId = e.RandString(20)
  145. v.Body = []byte(*body)
  146. jsonsvrparams := XConfig["JsonServerParamsPath"]
  147. if file, err := os.Open(jsonsvrparams); err == nil {
  148. if err = json.NewDecoder(file).Decode(&v.ServerParams); err != nil {
  149. return e.MyErr("LAAFDFDFERHYWE", err, true).Error()
  150. }
  151. } else {
  152. return e.MyErr("LAAFDFDWDERHYWE-"+jsonsvrparams+" File not found", err, true).Error()
  153. }
  154. if *params != "" { //User Params 있을 경우 해당을 가져온다.
  155. var askparmas []Param
  156. if err := json.Unmarshal([]byte(*params), &askparmas); err == nil {
  157. for _, j := range askparmas {
  158. for _, s := range v.ServerParams {
  159. if s.Key == j.Key {
  160. s.Value = j.Value
  161. } // 여기서 api-method 도 처리됨.
  162. }
  163. if j.Key == "ApiType" { // Ask Params 에 ApiType 이 지정되어 있다면
  164. v.ApiType = j.Value
  165. }
  166. if j.Key == "AskName" {
  167. v.AskName = j.Value
  168. }
  169. }
  170. } else {
  171. return e.MyErr("WERITOGFSERFDH-AskParams Format mismatched:", nil, true).Error()
  172. }
  173. } else {
  174. askfile := e.GetAskName()
  175. arrask := strings.Split(askfile, "@") // @앞의 문자를 askname으로 설정
  176. askname := arrask[0]
  177. apimethod := ""
  178. if len(arrask) >= 2 { //만약 argv[1] 이 login@Kafka 형태라면
  179. apimethod = arrask[1]
  180. }
  181. for i := 0; i < len(v.ServerParams); i++ {
  182. if v.ServerParams[i].Key == "api_method" { //GET, POST
  183. v.ServerParams[i].Value = apimethod
  184. }
  185. }
  186. v.ApiType = XConfig["ApiType"]
  187. v.AskName = askname
  188. }
  189. if v.ApiType == "" || v.AskName == "" {
  190. return e.MyErr("QWERDSFAERQRDA-ApiType or AskName was not specified:", nil, true).Error()
  191. }
  192. if retstr, retsta, err := MsgHandler(&v); err == nil {
  193. jsonreceive := XConfig["JsonReceiveDir"] + v.AskName + ".json"
  194. if XConfig["SaveReceivedJson"] == "Yes" {
  195. e.StrToFile(jsonreceive, retstr)
  196. }
  197. if XConfig["ShowReceivedJson"] == "Yes" {
  198. e.Tp("Status: " + retsta + " ReturnJsonFile: " + jsonreceive)
  199. e.Tp(retstr)
  200. }
  201. return retstr
  202. } else {
  203. return e.MyErr("QWERDSFAERQRDA-MsgHandler", err, true).Error()
  204. }
  205. }
  206. ///쓰이고 있지 않음.
  207. // func GetEnvConf() error { // Kangan only
  208. // conf := "conf/"
  209. // RunFilename := conf + "run_conf.json"
  210. // var run RunConf
  211. // if file, err := os.Open(RunFilename); err != nil {
  212. // e.MyErr("SDFLJDSAFJA", nil, true)
  213. // return err
  214. // } else {
  215. // decoder := json.NewDecoder(file)
  216. // if err = decoder.Decode(&run); err != nil {
  217. // e.MyErr("LASJLDFJASFJ", err, true)
  218. // return err
  219. // }
  220. // }
  221. // filename := conf + run.RunMode + run.ConfPostFix
  222. // if file, err := os.Open(filename); err != nil {
  223. // e.MyErr("QERTRRTRRW", err, true)
  224. // return err
  225. // } else {
  226. // decoder := json.NewDecoder(file)
  227. // if err = decoder.Decode(&XEnv); err != nil {
  228. // e.MyErr("LAAFDFERHY", err, true)
  229. // return err
  230. // }
  231. // }
  232. // if XEnv.DbType == "mysql" {
  233. // XEnv.DbStr = XEnv.DbUser + ":" + XEnv.DbPassword + "@tcp(" + XEnv.DbHost + ":" + XEnv.DbPort + ")/" + XEnv.DbPrefix + XEnv.DbName + "?charset=utf8"
  234. // } else if XEnv.DbType == "mssql" {
  235. // // Add on more DbStr of Db types
  236. // }
  237. // return nil
  238. // }
  239. func MyLinkXDB() { // 항상 연결될 수 있는 MySQL DB 사전 연결
  240. dbtype := XConfig["DbType"]
  241. connstr := XConfig["XDBConnString"] + XConfig["DBOptionString"]
  242. // connstr := XConfig["DbUser"] + ":" + XConfig["DbPassword"] + "@tcp(" + XConfig["DbHost"] + ":" + XConfig["DbPort"] + ")/" + XConfig["DbName"] + "?charset=utf8"
  243. var err error
  244. XDB, err = xorm.NewEngine(dbtype, connstr)
  245. strArr := strings.Split(connstr, "@tcp")
  246. if len(strArr) != 2 {
  247. e.MyErr(strArr[1], err, true)
  248. return
  249. }
  250. XDB.ShowSQL(false)
  251. XDB.SetMaxOpenConns(100)
  252. XDB.SetMaxIdleConns(20)
  253. XDB.SetConnMaxLifetime(60 * time.Second)
  254. if _, err := XDB.IsTableExist("aaa"); err != nil { //Connect Check
  255. e.MyErr("ASDFAERAFE-DATABASE DISCONNECTED", err, true)
  256. } else {
  257. e.OkLog("XDB CONNECTED :" + strArr[1])
  258. }
  259. }
  260. func MyLinkCrystalDB() { // Crystal Report Server
  261. dbtype := XConfig["DbType"]
  262. connstr := XConfig["CrystalDBConnString"] + XConfig["DBOptionString"]
  263. // connstr := XConfig["DbUser"] + ":" + XConfig["DbPassword"] + "@tcp(" + XConfig["DbHost"] + ":" + XConfig["DbPort"] + ")/" + XConfig["DbName"] + "?charset=utf8"
  264. var err error
  265. CrystalDB, err = xorm.NewEngine(dbtype, connstr)
  266. strArr := strings.Split(connstr, "@tcp")
  267. if len(strArr) != 2 {
  268. e.MyErr(strArr[1], err, true)
  269. return
  270. }
  271. CrystalDB.ShowSQL(false)
  272. CrystalDB.SetMaxOpenConns(100)
  273. CrystalDB.SetMaxIdleConns(20)
  274. CrystalDB.SetConnMaxLifetime(60 * time.Second)
  275. // Crystal Server가 죽어도 API 스타트에는 이상이 없도록 연결테스트는 아지 않는다.
  276. // if _, err := CrystalDB.IsTableExist("aaa"); err != nil { //Connect Check
  277. // e.OkLog("JHGKIUGBJ-CrystalDB Unconnected " + strArr[1])
  278. // // e.MyErr("JHGKIUGBJ-CrystalDB Unconnected ", err, true)
  279. // } else {
  280. // e.OkLog("CrystalDB Connected :" + strArr[1])
  281. // }
  282. }