aldikhan13

PUB/SUB using Channel in GO

Mar 17th, 2021
127
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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.  
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×