Dapr
Posted on June 2, 2022
Tags: devops
1 Pub/Sub
- Backend write api-endpoints that receive
/dapr/subscribe - Frontend writes to
http://localhost:<dapr-port>/v1.0/publish/<pub-sub-name>/<topic>
package main
import (
"encoding/json"
"io"
"log"
"net/http"
)
type Message struct {
Data struct {
Message string `json:"message"`
MessageType string `json:"messageType"`
} `json:"data"`
Datacontenttype string `json:"datacontenttype"`
ID string `json:"id"`
Pubsubname string `json:"pubsubname"`
Source string `json:"source"`
Specversion string `json:"specversion"`
Time string `json:"time"`
Topic string `json:"topic"`
Traceid string `json:"traceid"`
Traceparent string `json:"traceparent"`
Tracestate string `json:"tracestate"`
Type string `json:"type"`
}
type Subscription struct {
PubSubName string `json:"pubsubname"`
Topic string `json:"topic"`
Route string `json:"route"`
}
type MyServer struct {
}
func (p MyServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
subscriptions := []Subscription{
{"pubsub","A","A"},
{"pubsub","B","B"},
}
router := http.NewServeMux()
router.Handle("/dapr/subscribe", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
json.NewEncoder(w).Encode(subscriptions)
}
}))
for _,i := range subscriptions{
router.Handle("/"+i.Route, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodPost:
bodyBytes, _ := io.ReadAll(r.Body)
var msg Message
err := json.Unmarshal(bodyBytes,&msg)
errChk(err)
log.Println(msg)
msgJSON, err := json.MarshalIndent(msg, "", " ")
log.Println(string(msgJSON))
log.Println(string(bodyBytes))
w.WriteHeader(http.StatusOK)
case http.MethodGet:
log.Println("For Testing To see if Endpoint works")
w.WriteHeader(http.StatusOK)
}
}))
}
router.ServeHTTP(w, r)
}
func main(){
server := MyServer{}
http.ListenAndServe(":3000", server)
}
func errChk(x error){
if x != nil {
log.Println(x)
}
}go build .dapr run --app-id go-subscriber --app-port 3000 ./gosubexample log of received message
# == APP == 2022/12/25 22:29:10 {"data":{"message":"eqf","messageType":"A"},"datacontenttype":"application/json","id":"1093bf19-9e0f-4051-9e00-7d18efb3ffc9","pubsubname":"pubsub","source":"react-form","specversion":"1.0","time":"2022-12-25T22:29:10-05:00","topic":"A","traceid":"00-224350b06a7c660b80a1a6ba0751c0bf-fb8a24af533b7262-01","traceparent":"00-224350b06a7c660b80a1a6ba0751c0bf-fb8a24af533b7262-01","tracestate":"","type":"com.dapr.event.sent"}