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 {
struct {
Data string `json:"message"`
Message string `json:"messageType"`
MessageType } `json:"data"`
string `json:"datacontenttype"`
Datacontenttype string `json:"id"`
ID string `json:"pubsubname"`
Pubsubname string `json:"source"`
Source string `json:"specversion"`
Specversion string `json:"time"`
Time string `json:"topic"`
Topic string `json:"traceid"`
Traceid string `json:"traceparent"`
Traceparent string `json:"tracestate"`
Tracestate string `json:"type"`
Type }
type Subscription struct {
string `json:"pubsubname"`
PubSubName string `json:"topic"`
Topic string `json:"route"`
Route }
type MyServer struct {
}
func (p MyServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
:= []Subscription{
subscriptions {"pubsub","A","A"},
{"pubsub","B","B"},
}
:= http.NewServeMux()
router .Handle("/dapr/subscribe", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
routerswitch r.Method {
case http.MethodGet:
.NewEncoder(w).Encode(subscriptions)
json}
}))
for _,i := range subscriptions{
.Handle("/"+i.Route, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
routerswitch r.Method {
case http.MethodPost:
, _ := io.ReadAll(r.Body)
bodyBytesvar msg Message
:= json.Unmarshal(bodyBytes,&msg)
err (err)
errChk
.Println(msg)
log, err := json.MarshalIndent(msg, "", " ")
msgJSON.Println(string(msgJSON))
log.Println(string(bodyBytes))
log.WriteHeader(http.StatusOK)
w
case http.MethodGet:
.Println("For Testing To see if Endpoint works")
log.WriteHeader(http.StatusOK)
w}
}))
}
.ServeHTTP(w, r)
router}
func main(){
:= MyServer{}
server .ListenAndServe(":3000", server)
http}
func errChk(x error){
if x != nil {
.Println(x)
log}
}
go build .
dapr run --app-id go-subscriber --app-port 3000 ./gosub
example 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"}