Skip to content

Instantly share code, notes, and snippets.

@rozanecm
Last active February 22, 2021 14:11
Show Gist options
  • Save rozanecm/52e8f3be550b743f15e47043ef92e8c8 to your computer and use it in GitHub Desktop.
Save rozanecm/52e8f3be550b743f15e47043ef92e8c8 to your computer and use it in GitHub Desktop.
Go http
package main
import (
"encoding/json"
"log"
"net/http"
)
func initHttpServer() {
http.HandleFunc("/statusCheck", statusCheckHandler)
go func() { log.Fatal(http.ListenAndServe(":8080", nil)) } ()
}
func statusCheckHandler(writer http.ResponseWriter, request *http.Request) {
msg := map[string]string{"Status": "Ok"}
msgJSON, _ := json.Marshal(msg)
writer.WriteHeader(200)
_, _ = writer.Write(msgJSON)
}
func initHttpServer(nodes *map[string]int64) {
http.HandleFunc("/heartbeat", heartbeatHandler(nodes))
http.HandleFunc("/", home)
log.Fatal(http.ListenAndServe(":8080", nil))
}
func home(w http.ResponseWriter, r *http.Request) {
fmt.Println("Hello, world!")
}
func heartbeatHandler(nodes *map[string]int64) http.HandlerFunc {
return func(writer http.ResponseWriter, request *http.Request) {
type ExpectedResponse struct {
Name string `json:"Name"`
}
var eR ExpectedResponse
// Try to decode the request body into the struct. If there is an error,
// respond to the client with the error message and a 400 status code.
err := json.NewDecoder(request.Body).Decode(&eR)
if err != nil {
http.Error(writer, err.Error(), http.StatusBadRequest)
return
}
nodesCopy := *nodes
nodesCopy[eR.Name] = time.Now().Unix()
*nodes = nodesCopy
fmt.Printf("Nodes after update: %v\n", *nodes)
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"github.com/jasonlvhit/gocron"
"net/http"
)
func noLeaderTasks(nodeName string, leaderName string) {
msg := map[string]string{"Name": nodeName}
msgJSON, _ := json.Marshal(msg)
gocron.Start()
_ = gocron.Every(1).Second().Do(sendHeartbeat, msgJSON, leaderName)
for {
}
}
func sendHeartbeat(jsonValue []byte, leaderName string) {
url := "http://" + leaderName + ":8080/heartbeat"
_, err := http.Post(url,
"application/json",
bytes.NewBuffer(jsonValue))
if err != nil {
fmt.Printf("an error occurred during POST request: %s\n", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment