Skip to content

Instantly share code, notes, and snippets.

@keith6014
Created January 1, 2019 23:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keith6014/db470f8e5ab3b6ef211218fecee3e48e to your computer and use it in GitHub Desktop.
Save keith6014/db470f8e5ab3b6ef211218fecee3e48e to your computer and use it in GitHub Desktop.
sync map
package main
import (
"fmt"
"log"
"net/http"
"os/exec"
"strings"
"sync"
"time"
)
/* test cases
curl localhost:8080/?key='ps%20aux'
curl localhost:8080/?key='date%20-u'
curl localhost:8080/?key='uptime'
//go run -race main.go
*/
func mainhandler(w http.ResponseWriter, r *http.Request) {
key := r.FormValue("key")
log.Println("key->", key)
v, ok := myMap.Load(key)
if ok {
log.Printf("found %s\n", key)
fmt.Fprintf(w, "%s", v)
} else {
fmt.Fprintf(w, "%s not found\n", key)
}
}
func getallkeys(w http.ResponseWriter, r *http.Request) {
log.Println("Showing all keys")
keys := make([]string, 1)
myMap.Range(func(k, v interface{}) bool {
keys = append(keys, k.(string))
return true
})
fmt.Fprintf(w, "%v", keys)
}
var (
myMap sync.Map
)
func exeSomething(command string, tck *time.Ticker) {
for t := range tck.C {
log.Printf("running %s\t%v\n", command, t)
args := strings.Split(command, " ")
cmd := exec.Command(args[0], args[1:]...)
output, err := cmd.Output()
if err != nil {
return
}
myMap.Store(command, output)
}
}
func main() {
go exeSomething("uptime", time.NewTicker(time.Second*time.Duration(5)))
go exeSomething("date -u", time.NewTicker(time.Second*time.Duration(7)))
go exeSomething("ps aux", time.NewTicker(time.Second*time.Duration(7)))
mux := http.NewServeMux()
mux.HandleFunc("/", mainhandler)
mux.HandleFunc("/keys", getallkeys)
http.ListenAndServe(":8080", mux)
}
@tgulacsi
Copy link

tgulacsi commented Jan 2, 2019

A simple sync.RWMutex with a typed map[string]string would be better.

@rogierlommers
Copy link

Can you explain why this would be better?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment