Created
January 1, 2019 23:28
-
-
Save keith6014/db470f8e5ab3b6ef211218fecee3e48e to your computer and use it in GitHub Desktop.
sync map
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
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
A simple sync.RWMutex with a typed map[string]string would be better.