Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

68 lines
1.9KB

  1. package main
  2. import (
  3. "encoding/json"
  4. "io/ioutil"
  5. "log"
  6. "os"
  7. )
  8. //chat state that we might be use for collecting infomation from user
  9. type chatState struct {
  10. Name string `json:"Name"` //state name
  11. Expire int32 `json:"Expire"` //unix timestamp when this state expire
  12. Send struct { //anything we need to send?
  13. Type string `json:"Type"` //what type of message
  14. Message map[string]string `json:"Message"` //the message to be sent,key value pair to describe the message
  15. } `json:"Send"`
  16. Receive struct { //anything we expect to receive
  17. Validator string `json:"Validator"`
  18. Hint string `json:"Hint"`
  19. Message map[string]string `json:"Message"` //the description for receiving message
  20. } `json:"Receive"`
  21. }
  22. //for individual state
  23. func getCurrentState(openID string, procedure string) (result chatState, err error) {
  24. path := getProcedurePath(openID, procedure)
  25. log.Printf("read state from %s\r\n", path)
  26. body, err := ioutil.ReadFile(path)
  27. if err != nil { //read file error
  28. if isFileExist(path) {
  29. log.Println("Error session reading " + path)
  30. }
  31. return //empty and expired session
  32. }
  33. err = json.Unmarshal(body, &result)
  34. if err != nil {
  35. log.Printf("Session Content [path=%s] not correct: ", path)
  36. log.Println(err)
  37. }
  38. //we don't check Expire, we give the caller full control on
  39. //how to deal wiht expired session
  40. return
  41. }
  42. func setCurrentState(openID, procedure string, state chatState) (newState chatState, err error) {
  43. j, err := json.Marshal(state)
  44. if err != nil {
  45. return
  46. }
  47. path := getProcedurePath(openID, procedure)
  48. err = ioutil.WriteFile(path, j, 0600)
  49. if err != nil {
  50. log.Println("write state error" + path)
  51. log.Println(err)
  52. return
  53. }
  54. newState = state
  55. return
  56. }
  57. func deleteChatState(openID, procedure string) (err error) {
  58. path := getProcedurePath(openID, procedure)
  59. err = os.Remove(path)
  60. return
  61. }