restful-api.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package restful_api
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "net/http"
  5. )
  6. type StatsUser struct {
  7. uuid string `form:"uuid" binging:"required_without=email,uuid4"`
  8. email string `form:"email" binging:"required_without=uuid,email"`
  9. }
  10. func statsUser(c *gin.Context) {
  11. var statsUser StatsUser
  12. if err := c.BindQuery(&statsUser); err != nil {
  13. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  14. }
  15. c.JSON(http.StatusOK, gin.H{
  16. "uplink": 1,
  17. "downlink": 1,
  18. })
  19. }
  20. type Stats struct {
  21. tag string `form:"tag" binging:"required,alpha,min=1,max=255"`
  22. }
  23. type StatsBound struct { // Better name?
  24. Uplink int64 `json:"uplink"`
  25. Downlink int64 `json:"downlink"`
  26. }
  27. type StatsResponse struct {
  28. Inbound StatsBound `json:"inbound"`
  29. Outbound StatsBound `json:"outbound"`
  30. }
  31. func stats(c *gin.Context) {
  32. var stats Stats
  33. if err := c.BindQuery(&stats); err != nil {
  34. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  35. }
  36. response := StatsResponse{
  37. Inbound: StatsBound{
  38. Uplink: 1,
  39. Downlink: 1,
  40. },
  41. Outbound: StatsBound{
  42. Uplink: 1,
  43. Downlink: 1,
  44. }}
  45. c.JSON(http.StatusOK, response)
  46. }
  47. func loggerReboot(c *gin.Context) {
  48. c.JSON(http.StatusOK, gin.H{})
  49. }
  50. func TokenAuthMiddleware() gin.HandlerFunc {
  51. return func(c *gin.Context) {
  52. auth := c.GetHeader("Authorization")
  53. if auth[6:] != "token123" { // tip: Bearer: token123
  54. c.JSON(http.StatusUnauthorized, "unauthorized")
  55. c.Abort()
  56. return
  57. }
  58. c.Next()
  59. }
  60. }
  61. func Start() error {
  62. r := gin.New()
  63. r.GET("/ping", func(c *gin.Context) {
  64. c.JSON(200, gin.H{
  65. "message": "pong",
  66. })
  67. })
  68. v1 := r.Group("/v1")
  69. v1.Use(TokenAuthMiddleware())
  70. {
  71. v1.GET("/stats/user", statsUser)
  72. v1.GET("/stats", stats)
  73. v1.POST("/logger/reboot", loggerReboot)
  74. }
  75. if err := r.Run(":3000"); err != nil {
  76. return err
  77. }
  78. return nil
  79. }