Last active
September 20, 2024 09:16
-
-
Save loderunner/5598eded0409e47acaf5cdcf7855f591 to your computer and use it in GitHub Desktop.
Websocket with Gin in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"math/rand" | |
"net/http" | |
"time" | |
"github.com/gorilla/websocket" | |
) | |
type DataPoint struct { | |
Timestamp time.Time `json:"timestamp"` | |
Temperature float32 `json:"temperature"` | |
} | |
func main() { | |
conn, _, err := websocket.DefaultDialer.Dial("ws://localhost:8888/data", http.Header{}) | |
if err != nil { | |
panic(err.Error()) | |
} | |
ticker := time.Tick(2 * time.Second) | |
for { | |
select { | |
case <-ticker: | |
dataPoint := DataPoint{ | |
Timestamp: time.Now(), | |
Temperature: float32(rand.NormFloat64()*5 + 20), | |
} | |
fmt.Printf("[%s] %.2fºC\n", | |
dataPoint.Timestamp.Format(time.RFC3339), | |
dataPoint.Temperature, | |
) | |
err = conn.WriteJSON(dataPoint) | |
if err != nil { | |
panic(err.Error()) | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"errors" | |
"fmt" | |
"net/http" | |
"time" | |
"github.com/gin-gonic/gin" | |
"github.com/gorilla/websocket" | |
) | |
type DataPoint struct { | |
Timestamp time.Time `json:"timestamp"` | |
Temperature float32 `json:"temperature"` | |
} | |
var upgrader websocket.Upgrader | |
func data(ctx *gin.Context) { | |
c, err := upgrader.Upgrade(ctx.Writer, ctx.Request, nil) | |
if err != nil { | |
ctx.AbortWithError(http.StatusInternalServerError, err) | |
return | |
} | |
defer c.Close() | |
var dataPoint DataPoint | |
for err := c.ReadJSON(&dataPoint); err == nil; err = c.ReadJSON(&dataPoint) { | |
fmt.Printf( | |
"[%s] %.2fºC\n", | |
dataPoint.Timestamp.Format(time.RFC3339), | |
dataPoint.Temperature, | |
) | |
} | |
if err != nil { | |
ctx.AbortWithError(http.StatusInternalServerError, err) | |
return | |
} | |
ctx.Status(http.StatusOK) | |
} | |
func main() { | |
r := gin.Default() | |
r.GET("/data", data) | |
err := r.Run(":8888") | |
if !errors.Is(err, http.ErrServerClosed) { | |
panic(err.Error()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment