abango.go 8.9 KB

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