初级会员
  • 第 16916 位会员
  • zhanghc
  • 2018-03-16 17:54:49
  • Offline
  • 19 85

最近发布的主题

    暂无

最近发布的文章

    暂无

最近分享的资源

    暂无

最近发布的项目

    暂无

最近的评论

  • url := "https://pic.cnblogs.com/face/725163/20150226170205.png" header,err := http.Head(url) if err != nil { log.Fatal(err) } fmt.Println(header.ContentLength)
  • package main import( "fmt" "math/rand" ) func main() { var i int64 a(&i) fmt.Println(i) a(&i) fmt.Println(i) a(&i) fmt.Println(i) } func a(a *int64) error { if *a == 0 { *a = int64(rand.Int()) } return nil }
  • 😄。你可以考虑 做 etcd 多个节点 + 报警,这样可以 1、完成 平滑部署与维护 2、异常退出 服务不会中断
  • package main import ( "os/exec" "bytes" "log" "net/http" "runtime" "io/ioutil" "io" "fmt" "encoding/json" "strings" ) type HttpHandler struct { MetricsChannel chan string DataChannel chan string } func NewHttpHandler() *HttpHandler { return &HttpHandler{ MetricsChannel: nil, DataChannel: nil, } } func(handler *HttpHandler) ExecShell(s string) (string){ var out bytes.Buffer cmd := exec.Command("/bin/bash", "-c", s) cmd.Stdout = &out if err := cmd.Run();err != nil { return err.Error() } return out.String() } func(handler *HttpHandler) Consume(data []string) { defer close(handler.MetricsChannel) for _, cmd := range data { handler.MetricsChannel <- cmd } } func(handler *HttpHandler) Product() { defer close(handler.DataChannel) for { cmd,ok := <- handler.MetricsChannel if !ok { break } r := handler.ExecShell(cmd) fmt.Println("process:",cmd,r) handler.DataChannel <- r } } func(handler *HttpHandler) Process(data []string) (string, error) { handler.MetricsChannel = make(chan string,10) handler.DataChannel = make(chan string,10) go handler.Consume(data) go handler.Product() result := make([]string,0) for { data,ok := <- handler.DataChannel if !ok { break } result = append(result,data) } return strings.Join(result,"\n"),nil } func(handler *HttpHandler) Metrics(w http.ResponseWriter, r *http.Request) { var err error body, err := ioutil.ReadAll(r.Body) if err != nil { log.Fatal(err) } response, err := handler.Process(handler.ParseRequest(body)) if err != nil { io.WriteString(w,fmt.Sprintf("error happened:%s",err.Error())) } io.WriteString(w,response) } func (handler *HttpHandler) ParseRequest(str []byte) []string { var data []string json.Unmarshal(str,&data) return data } func main(){ runtime.GOMAXPROCS(runtime.NumCPU()) httpHandler := NewHttpHandler() http.HandleFunc("/metrics",httpHandler.Metrics) err := http.ListenAndServe(":8888", nil) if err != nil { log.Fatal("ListenAndServe:", err) } }