Last active
August 4, 2019 14:28
-
-
Save maderaka/7180ffd74c83382dc412 to your computer and use it in GitHub Desktop.
An example of using Golang Martini & NSQ
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 ( | |
"encoding/json" | |
"fmt" | |
"github.com/bitly/go-nsq" | |
"github.com/codegangsta/inject" | |
"github.com/go-martini/martini" | |
"log" | |
"net/http" | |
"reflect" | |
) | |
func main() { | |
// Initialize martini | |
m := martini.Classic() | |
m.Map(myReturnHandler()) | |
// Register some services | |
m.MapTo(&User{}, (*UserInterface)(nil)) | |
// App routes | |
routes(m) | |
// Use middleware | |
middleware(m) | |
// Register consumer | |
consumer() | |
// Run application server | |
m.Run() | |
} | |
func myReturnHandler() martini.ReturnHandler { | |
return func(ctx martini.Context, vals []reflect.Value) { | |
rv := ctx.Get(inject.InterfaceOf((*http.ResponseWriter)(nil))) | |
res := rv.Interface().(http.ResponseWriter) | |
var responseVal reflect.Value | |
var status int = 200 | |
if len(vals) > 1 && vals[0].Kind() == reflect.Int { | |
status = int(vals[0].Int()) | |
res.WriteHeader(status) | |
responseVal = vals[1] | |
} else if len(vals) > 0 { | |
responseVal = vals[0] | |
} | |
content := responseVal.Interface() | |
res.Header().Set("Content-Type", "application/json") | |
json.NewEncoder(res).Encode(map[string]interface{}{ | |
"data": content, | |
"status": status, | |
}) | |
} | |
} | |
func routes(m martini.Router) { | |
// Make it more simple :)) | |
route := m.AddRoute | |
// Register some endpoints | |
route("GET", "/love/:you", loveYou) | |
route("GET", "/ping", ping) | |
} | |
func loveYou(params martini.Params) interface{} { | |
// Publish an event to your love | |
defer func() { | |
if r := recover(); r != nil { | |
fmt.Println("Recovered in f", r) | |
} | |
}() | |
publisher(params["you"], w) | |
// Return your love as diamonds | |
// Make sure, she know about your feelings | |
return struct { | |
Id int `json:"id"` | |
FirstName string `json:"first_name"` | |
Email string `json:"email"` | |
}{ | |
92, | |
params["you"], | |
"rakatejaa@gmail.com", | |
} | |
} | |
func ping(user UserInterface) string { | |
return user.Ping() | |
} | |
// Use middleware | |
func middleware(m *martini.ClassicMartini) { | |
m.Use(func(res http.ResponseWriter, req *http.Request) { | |
if req.Header.Get("X-API-KEY") != "12345" { | |
res.WriteHeader(http.StatusUnauthorized) | |
} | |
}) | |
m.Use(func(c martini.Context, log *log.Logger, res http.ResponseWriter) { | |
log.Println("Before request route") | |
c.Next() | |
log.Println("After request route") | |
}) | |
} | |
// An interface of user | |
type UserInterface interface { | |
Ping() string | |
} | |
// An user for manage any love inside | |
type User struct { | |
} | |
// Ping your love | |
// Make sure it works | |
func (user *User) Ping() string { | |
return fmt.Sprintf("Love everyone forever") | |
} | |
// ------------------------------------------------------- | |
// NSQ, Queue Messaging | |
// ------------------------------------------------------- | |
var nsqHost = "127.0.0.1:4150" | |
var config = nsq.NewConfig() | |
var w, _ = nsq.NewProducer(nsqHost, config) | |
func publisher(name string, w *nsq.Producer) { | |
err := w.Publish("love", []byte(name)) | |
if err != nil { | |
log.Panic("Could not connect") | |
} | |
} | |
func consumer() { | |
q, _ := nsq.NewConsumer("love", "default", config) | |
q.AddHandler(nsq.HandlerFunc(func(message *nsq.Message) error { | |
log.Println("I don't love you : %s", string(message.Body)) | |
return nil | |
})) | |
err := q.ConnectToNSQD(nsqHost) | |
if err != nil { | |
log.Panic("Could not connect") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment