handler.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package friend
  2. import (
  3. "fmt"
  4. "net/http"
  5. "prime/user"
  6. . "prime/basic"
  7. "github.com/gin-gonic/gin"
  8. )
  9. func init() {
  10. r := user.Authorized
  11. r.GET("applications", getApplicationsHandler)
  12. r.POST("application", postApplicationHandler)
  13. r.PATCH("application", patchApplicationHandler)
  14. r.GET("friends", getFriendsHandler)
  15. }
  16. func getFriendsHandler(c *gin.Context) {
  17. uid := c.MustGet("uid").(uint)
  18. friends, err := GetFriends(uid)
  19. fmt.Println(friends)
  20. if err == nil {
  21. c.JSON(http.StatusOK, gin.H{"friends": friends})
  22. } else {
  23. c.JSON(ErrCode(err), gin.H{"error": err.Error()})
  24. }
  25. }
  26. func getApplicationsHandler(c *gin.Context) {
  27. uid := c.MustGet("uid").(uint)
  28. apps, err := GetApplications(uid)
  29. if err == nil {
  30. c.JSON(http.StatusOK, gin.H{"apps": apps})
  31. } else {
  32. c.JSON(ErrCode(err), gin.H{"error": err.Error()})
  33. }
  34. }
  35. func postApplicationHandler(c *gin.Context) {
  36. uid := c.MustGet("uid").(uint)
  37. var form struct {
  38. Receiver uint `json:"receiver" binding:"required"`
  39. Message []byte `json:"message" binding:"required"`
  40. }
  41. if err := c.Bind(&form); err == nil {
  42. appID, err := ApplyFriend(uid, form.Receiver, form.Message)
  43. if err == nil {
  44. c.JSON(http.StatusOK, gin.H{"appid": appID})
  45. } else {
  46. c.JSON(ErrCode(err), gin.H{"error": err.Error()})
  47. }
  48. } else {
  49. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  50. }
  51. }
  52. func patchApplicationHandler(c *gin.Context) {
  53. uid := c.MustGet("uid").(uint)
  54. fmt.Printf("uid=%d\n", uid)
  55. var form struct {
  56. AppID uint `json:"appid" binding:"required"`
  57. Reply int `json:"reply" binding:"required"`
  58. }
  59. if err := c.Bind(&form); err == nil {
  60. fmt.Printf("%+v\n", form)
  61. err := ReplyApplication(uid, form.AppID, form.Reply > 0)
  62. if err == nil {
  63. c.JSON(http.StatusOK, gin.H{"status": "ok"})
  64. } else {
  65. c.JSON(ErrCode(err), gin.H{"error": err.Error()})
  66. }
  67. } else {
  68. // TODO: 发送reply为0则无法读取???
  69. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  70. panic(err)
  71. }
  72. }