Golang single point push

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.
Package Mainimport ("Encoding/json" "Flag" "FMT" "Log" "Net/http" "Time" "config" "Framework/logger" "Global" models/ function "" Models/schema "" Github.com/go-redis/redis "" Github.com/gorilla/websocket "" Github.com/labstack/echo ") var clients = make (map[*websocket. Conn]bool) var broadcast = make (Chan Message) var upgrader = WebSocket. Upgrader{checkorigin:func (R *http. Request) bool {return true}}//Do not use default settings if the online environment may need to use the default configuration var Chananel = Make (chan schema. Listening)//Data Chanvar configfile *string = flag. String ("config", "./bin/etc/conf.yaml", "agency config file")//This is the database profile parsing, which is presented at the time of the single write Var agentslice []map[string]* WebSocket. Conn//socket Correspondence Relationship store//Send message struct type message struct {message interface{} ' JSON: ' Message ' ' SiteId string ' json: ' site_id ' Siteindexid string ' JSON: ' site_index_id ' ' Count Int64 ' JSON: ' Count ' '}//tested with [a formal modification can be removed after]func Hu (w http. Responsewriter, R *http. Request) {SiteID: = R.formvalue ("site_id") Siteindexid: = R.formvalue ("site_index_id") fmt. Println (Siteindexid, SiteID) S: = Schema. listening{"Zym", "B", 1}chananel <-S}func Main () {//Database initialize CFG, err: = config. Parseconfigfile (*configfile) if err! = Nil {log. Fatalf ("parse config file error:%v\n", err. Error ()) return}//Initialize Database err = Global. Initmysql (CFG. MYSQLS) If err! = Nil {///database connection error Global. Globallogger.error ("Initdb error:%v\n", err. Error ()) return}http. Handlefunc ("/o", HU) http. Handlefunc ("/ws", handleconnections) go handlemessages () Err = http. Listenandserve (CFG. Wesocketport, nil) if err! = Nil {log. Fatal (Err. Error ())}}func handleconnections (w http. Responsewriter, R *http. Request) {//If you restrict the connection you can use the Ip+port limit, differentiate the client according to IP, others can be based on R. Request submitted data to find the appropriate content SiteID: = R.formvalue ("site_id") Siteindexid: = R.formvalue ("site_index_id")// Here is the only way to differentiate the client's judgment if siteId = = "" | | Siteindexid = = "" {http. Error (W, "site_id and site_index_id must not empty", 403)}//registered as WEBSOCKETWS, err: = Upgrader. Upgrade (W, R, nil) if err! = Nil {Global. Globallogger.error ("error:%s", err. Error ()) Return}defer ws. Close ()///storage connection [Todo here may also consider map concurrency read-write issues]agent: = Make (Map[string]*websocket. Conn) Agent[s] = Wsagentslice = Append (Agentslice, agent) Clients[ws] = true//listener receives a [Models/schema]schema. listening,for {var msg Messages: = <-chananelif S.types = = 1 {//todo The data extracted here may also need to be processed//get the latest unconfirmed company deposit Newincome: = new ( function. Membercompanyincomebean) info, count, err: = Newincome. Getnotconfirm (S.siteid, S.SITEINDEXID) if err! = Nil {Global. Globallogger.error ("error:%s", err. Error ()) return}msg = Message{siteindexid:s.siteindexid, Siteid:s.siteid, Message:info, Count:count}} else if S.Types = = 2 {//Get latest on-line deposit Onlinebean: = new (function. Onlineentryrecordbean) info, count, err: = Onlinebean.getnotconfirm (S.siteid, S.SITEINDEXID) if err! = Nil {Global. Globallogger.error ("error:%s", err. Error ()) return}msg = Message{siteindexid:s.siteindexid, Siteid:s.siteid, Message:info, Count:count}} else {//Get the most New out-of-the-money management Makemoney: = new (function. Makemoneybean) info, count, err: = Makemoney.getoperaterecord (S.siteid, S.SITEINDEXID) if err! = Nil {Global. Globallogger.error ("error:%s", err. Error ()) return}msg = Message{siteindexid:s.siteindexid, Siteid:s.siteid, Count:count, Message:info}}broadcast <-msg}}//single Click to push the Func handlemessages () {for {msg: = <-broadcastvar pushclient []*websocket. Connnews: = Fmt. Sprintf ("%s%s", Msg. SiteId, Msg. SITEINDEXID) Lenagent: = Len (agentslice) for I: = 0; i < lenagent; i++ {for k, V: = Range Agentslice[i] {if NewS = = k {pushclient = append (pushclient, v)}}}for I: = 0; I < Len (pushclient); i++ {for client: = Range Clients {if pushclient[i] = = Client {err: = client. Writejson (msg) if err! = Nil {Global. Globallogger.error ("error:%s", err. Error ()) client.  Close () Delete (clients, client)}}}}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.