Advertisement
aldikhan13

PUB/SUB using Channel in GO

Mar 17th, 2021
726
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.82 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "encoding/json"
  5.     "fmt"
  6.     "runtime"
  7.     "time"
  8. )
  9.  
  10. type Profile struct {
  11.     Name string `json:"name"`
  12.     Age  uint   `json:"age"`
  13. }
  14.  
  15. func Publisher(data string, channel chan interface{}) {
  16.     channel <- string(data)
  17. }
  18.  
  19. func Subscribe(channel chan interface{}) {
  20.     profile := <-channel
  21.     fmt.Println(profile)
  22. }
  23.  
  24. func main() {
  25.     // set core max to use for gorutine
  26.     runtime.GOMAXPROCS(2)
  27.  
  28.     // init channel
  29.     profileChannel := make(chan interface{})
  30.  
  31.     // set value for struct
  32.     var profile Profile
  33.     profile.Name = "john doe"
  34.     profile.Age = 23
  35.  
  36.     // convert to json
  37.     toJson, _ := json.Marshal(profile)
  38.  
  39.     // sending channel data
  40.     go Publisher(string(toJson), profileChannel)
  41.  
  42.     // get channel data
  43.     go Subscribe(profileChannel)
  44.  
  45.     // delay gorutine 1000 second
  46.     time.Sleep(time.Second * 1)
  47. }
  48.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement