http.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package server
  2. import (
  3. "fmt"
  4. "github.com/charmbracelet/log"
  5. "github.com/gin-gonic/gin"
  6. "github.com/sstallion/go-hid"
  7. "lianlinux/core"
  8. "net/http"
  9. "strconv"
  10. )
  11. type rootJSON struct {
  12. SupportedDevices []string `json:"SupportedDevices"`
  13. Devices []*hid.DeviceInfo `json:"Devices"`
  14. }
  15. type responseJSON struct {
  16. Status string `json:"Status"`
  17. Message string `json:"Message"`
  18. }
  19. func root(c *gin.Context) {
  20. c.IndentedJSON(http.StatusOK, rootJSON{
  21. SupportedDevices: []string{"a100"},
  22. Devices: core.Devs,
  23. })
  24. }
  25. func lightMode(c *gin.Context) {
  26. deviceNumber, err := strconv.Atoi(c.Query("dev"))
  27. if err != nil {
  28. c.Status(500)
  29. c.IndentedJSON(http.StatusOK, responseJSON{
  30. Status: "error",
  31. Message: fmt.Sprintf("%v", err),
  32. })
  33. return
  34. }
  35. newMode := c.Query("mode")
  36. if newMode == "" || deviceNumber > len(core.Devs) {
  37. c.Status(400)
  38. c.IndentedJSON(http.StatusOK, responseJSON{
  39. Status: "error",
  40. Message: "Mode is empty or device index out of bounds",
  41. })
  42. return
  43. }
  44. switch newMode {
  45. case "static", "morph", "rainbow":
  46. core.SetLightMode(*core.Devs[deviceNumber], newMode)
  47. c.IndentedJSON(http.StatusOK, responseJSON{
  48. Status: "ok",
  49. Message: fmt.Sprintf("Set device %d mode to %s", deviceNumber, newMode),
  50. })
  51. default:
  52. c.Status(400)
  53. c.IndentedJSON(http.StatusOK, responseJSON{
  54. Status: "error",
  55. Message: "Unknown mode",
  56. })
  57. }
  58. }
  59. func Listen(port int) {
  60. gin.SetMode(gin.ReleaseMode)
  61. router := gin.Default()
  62. router.GET("/", root)
  63. router.POST("/mode", lightMode)
  64. log.Infof("Listening on port %d", port)
  65. err := router.Run("localhost:" + strconv.Itoa(port))
  66. if err != nil {
  67. return
  68. }
  69. }