Skip to content

Instantly share code, notes, and snippets.

@mickelsonm
Last active August 29, 2015 14:14
Show Gist options
  • Save mickelsonm/8ab51cf6171f6aa3100d to your computer and use it in GitHub Desktop.
Save mickelsonm/8ab51cf6171f6aa3100d to your computer and use it in GitHub Desktop.
var(
requestQueue = nsqq.NewQueue("goapi")
)
func MyRequestHandler(res http.ResponseWriter, req *http.Request){
//collects information from request object
//builds a struct, serializes it into json, then sends it into helper
if requestQueue != nil{
js, err := json.Marshal(myStruct)
if err == nil{
requestQueue.Push(js)
}
}
}
package nsqq
import (
"io/ioutil"
"log"
"os"
"strings"
"github.com/bitly/go-nsq"
)
var (
nullLogger = log.New(ioutil.Discard, "", log.LstdFlags)
)
type Queue struct {
Topic string
ServerAddresses []string
Config *nsq.Config
Producers map[string]*nsq.Producer
}
func NewQueue(topicname string) *Queue {
q := Queue{
Topic: topicname,
Config: nsq.NewConfig(),
}
if hosts := os.Getenv("NSQ_DAEMON_HOSTS"); hosts != "" {
segs := strings.Split(hosts, ",")
q.ServerAddresses = segs
}
q.Init()
return &q
}
func (mq *Queue) Init() error {
if len(mq.ServerAddresses) == 0 {
mq.ServerAddresses = getDaemonHosts()
}
mq.Producers = make(map[string]*nsq.Producer)
for _, addr := range mq.ServerAddresses {
producer, err := nsq.NewProducer(addr, mq.Config)
if err != nil {
return err
}
producer.SetLogger(nullLogger, nsq.LogLevelInfo)
mq.Producers[addr] = producer
}
return nil
}
func (mq *Queue) Dispose() {
for _, p := range mq.Producers {
p.Stop()
}
}
func (mq *Queue) Push(data []byte) error {
for _, p := range mq.Producers {
if err := p.Publish(mq.Topic, data); err != nil {
return err
}
}
return nil
}
func getDaemonHosts() []string {
hostString := os.Getenv("NSQ_DAEMON_HOSTS")
if hostString == "" {
return []string{"127.0.0.1:4160"}
}
return strings.Split(hostString, ",")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment