update golang example

Signed-off-by: Sarthak Sharma <sartsharma@microsoft.com>
This commit is contained in:
Sarthak Sharma 2022-11-13 20:20:27 +05:30
parent de92117403
commit 96f054c2f6
3 changed files with 61 additions and 14 deletions

View File

@ -17,8 +17,7 @@ Pick a building block API (for example, pub-sub, state management) and rapidly t
| [Bindings](./bindings/) | Work with external systems using input bindings to respond to events and output bindings to call operations|
| [Secrets Management](./secrets_management/) | Securely fetch secrets |
| Actors | Coming soon... |
| Observability | Coming soon... |
| [Configuration](./configuration) | Consume configuration items as key/value pairs and subscribe to changes whenever a configuration item changes |
| [Configuration](./configuration) | Get configuration items as key/value pairs or subscribe to changes whenever a configuration item changes |
### Tutorials
Go deeper into a topic or scenario, oftentimes using building block APIs together to solve problems (for example, build a distributed calculator, build and deploy an app to Kubernetes).

View File

@ -1,6 +1,7 @@
package main
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
@ -8,6 +9,7 @@ import (
"net/http"
"os"
"strings"
"sync"
"time"
"github.com/gorilla/mux"
@ -41,15 +43,24 @@ func main() {
fmt.Println("Configuration for "+item+":", string(result))
}
// Create POST endpoint to receive config updates
go startServerToListen()
var subscriptionId string
wg := new(sync.WaitGroup)
wg.Add(2)
// Start HTTP Server to receive config updates for 20 seconds and then shutdown and unsubscribe from config updates
go func() {
startServerToListen(&subscriptionId)
wg.Done()
}()
// Subscribe for config updates
go subscribeToConfigUpdates()
// Block main goroutine for 15 seconds and then stop the app
time.Sleep(15 * time.Second)
go func() {
subscribeToConfigUpdates(&subscriptionId)
wg.Done()
}()
wg.Wait()
}
func subscribeToConfigUpdates() {
func subscribeToConfigUpdates(subscriptionId *string) {
// Add delay to allow app channel to be ready
time.Sleep(3 * time.Second)
@ -67,18 +78,55 @@ func subscribeToConfigUpdates() {
var subid map[string]interface{}
json.Unmarshal(sub, &subid)
fmt.Println("App subscribed to config changes with subscription id:", subid["id"])
return
*subscriptionId = subid["id"].(string)
} else {
fmt.Println("Error subscribing to config updates: ", string(sub))
os.Exit(1)
}
}
func startServerToListen() {
func startServerToListen(subscriptionId *string) {
r := mux.NewRouter()
httpServer := http.Server{
Addr: ":" + appPort,
Handler: r,
}
r.HandleFunc("/configuration/configstore/{configItem}", configUpdateHandler).Methods("POST")
if err := http.ListenAndServe(":"+appPort, r); err != nil {
log.Panic(err)
// Shutdown Server after 20 seconds
time.AfterFunc(20*time.Second, func() {
err := httpServer.Shutdown(context.Background())
if err != nil {
fmt.Println("Error shutting down HTTP server, err:" + err.Error())
}
})
// Register shutdown function
httpServer.RegisterOnShutdown(func() {
fmt.Println("Shutting down HTTP server")
unsubscribeFromConfigUpdates(*subscriptionId)
})
// Start HTTP server
if err := httpServer.ListenAndServe(); err != nil {
log.Println("HTTP server error:", err)
}
}
func unsubscribeFromConfigUpdates(subscriptionId string) {
unsubscribe, err := http.Get(DAPR_HOST + ":" + DAPR_HTTP_PORT + "/v1.0-alpha1/configuration/" + DAPR_CONFIGURATION_STORE + "/" + subscriptionId + "/unsubscribe")
if err != nil {
fmt.Println("Error unsubscribing from config updates, err:" + err.Error())
}
unsub, err := ioutil.ReadAll(unsubscribe.Body)
if err != nil {
fmt.Print("Unable to read unsubscribe response, err: " + err.Error())
}
if strings.Contains(string(unsub), "true") {
fmt.Println("App unsubscribed from config changes")
return
} else {
fmt.Println("Error unsubscribing from config updates: ", string(unsub))
}
}

View File

@ -19,7 +19,7 @@ func main() {
if err != nil {
log.Panic(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
// Get config items from config store
@ -49,7 +49,7 @@ func main() {
os.Exit(1)
}
// Exit app after 15 seconds
// Exit app after 20 seconds
select {
case <-ctx.Done():
os.Exit(0)