util.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package tick
  2. import (
  3. "net/http"
  4. "tickserver/server/market"
  5. )
  6. import "io/ioutil"
  7. import "crypto/rand"
  8. import "encoding/json"
  9. import "encoding/hex"
  10. //import "log"
  11. //在检查之前,确定已经登录
  12. type JsonResponse struct {
  13. Result interface{} `json:"result"`
  14. Err string `json:"err"`
  15. Code int `json:"code"`
  16. }
  17. func NewJsonResponse(data interface{}, err string, code int) *JsonResponse {
  18. resp := &JsonResponse{}
  19. resp.Result = data
  20. resp.Err = err
  21. resp.Code = code
  22. return resp
  23. }
  24. func readRequest(w http.ResponseWriter, r *http.Request) ([]byte, error) {
  25. data, err := ioutil.ReadAll(r.Body)
  26. if err != nil {
  27. return nil, err
  28. }
  29. return data, nil
  30. }
  31. func decodeRequestInner(w http.ResponseWriter, r *http.Request, data []byte, v interface{}) error {
  32. err := json.Unmarshal(data, v)
  33. if err != nil {
  34. return err
  35. }
  36. return err
  37. }
  38. func decodeRequest(w http.ResponseWriter, r *http.Request, v interface{}) error {
  39. data, err := readRequest(w, r)
  40. if err != nil {
  41. return err
  42. }
  43. return decodeRequestInner(w, r, data, v)
  44. }
  45. func sendErrResponse(w http.ResponseWriter, r *http.Request, code int, err string) {
  46. w.WriteHeader(code)
  47. res := NewJsonResponse(nil, err, -1)
  48. s, _ := json.Marshal(res)
  49. w.Write(s)
  50. }
  51. func sendResponse(w http.ResponseWriter, r *http.Request, data interface{}) {
  52. w.WriteHeader(http.StatusOK)
  53. res := NewJsonResponse(data, "", 0)
  54. s, err := json.Marshal(res)
  55. if err != nil {
  56. sendErrResponse(w, r, 200, err.Error())
  57. return
  58. }
  59. w.Write(s)
  60. }
  61. func getId() string {
  62. var b [5]byte
  63. rand.Read(b[:])
  64. return hex.EncodeToString(b[:])
  65. }
  66. func checkTime(exId string, ts int64) bool {
  67. var tis []tInterval
  68. switch exId {
  69. case "SHFE": // 上海期货交易所
  70. tis = shefTi
  71. case "CFFEX": // 中国金融期货交易所
  72. tis = cffexTi
  73. case "DCE", "CZCE": //大连、郑州商品交易所
  74. tis = decAndCzceTi
  75. default:
  76. panic("can't go here")
  77. }
  78. t := market.GetTime(ts)
  79. //log.Println("debug checktime", t)
  80. mm := t.Hour()*60 + t.Minute()
  81. for _, ti := range tis {
  82. m1 := ti.st.hour*60 + ti.st.minute
  83. m2 := ti.et.hour*60 + ti.et.minute
  84. if mm >= m1 && mm <= m2 {
  85. return true
  86. }
  87. }
  88. return false
  89. }