美文网首页GO
GO: web服务器

GO: web服务器

作者: 随风化作雨 | 来源:发表于2017-11-20 10:22 被阅读16次
    [root@localhost eGW]# cat webserver.go
    package main
    
    import (
        "encoding/json"
        "fmt"
        "io/ioutil"
        "log"
        "net/http"
        "os/exec"
        "strings"
    )
    
    type User struct {
        Name string `json:"name"`
        Age  int    `json:"age"`
    }
    
    type Cmd_Resp struct {
        Cmd  string   `json:"cmd"`
        Resp []string `json:"resp"`
        //Lst string `json:"lst"`
        //Mod string `json:"mod"`
        //Add string `json:"add"`
        //Del string `json:"del"`
    }
    
    func index(w http.ResponseWriter, r *http.Request) {
        r.ParseForm()
        fmt.Println("Form: ", r.Form)
        fmt.Println("Path: ", r.URL.Path)
        fmt.Println(r.Form["a"])
        fmt.Println(r.Form["b"])
        for k, v := range r.Form {
            fmt.Println(k, "=>", v, strings.Join(v, "-"))
        }
        fmt.Fprint(w, "It works!")
    }
    
    func test(w http.ResponseWriter, r *http.Request) {
        body, _ := ioutil.ReadAll(r.Body)
        body_str := string(body)
        fmt.Println(body_str)
        //var user User
        //if err := json.Unmarshal(body, &user); err == nil {
        //  fmt.Println(user)
        //  user.Name = "liyu"
        //  user.Age += 100
        //  fmt.Println(user)
        //  ret, _ := json.Marshal(user)
        //  fmt.Fprint(w, string(ret))
        //} else {
        //  fmt.Println(err)
        //}
        var cmd_resp Cmd_Resp
        if err := json.Unmarshal(body, &cmd_resp); err == nil {
            fmt.Println(cmd_resp)
            fmt.Println(cmd_resp.Cmd)
            if len(cmd_resp.Cmd) > 0 {
                _output, _ := exec.Command("/bin/bash", "-c", cmd_resp.Cmd).Output()
                output := strings.Split(string(_output), "\n")
                cmd_resp.Resp = output
                fmt.Println(cmd_resp)
                ret, _ := json.Marshal(cmd_resp)
                fmt.Fprint(w, string(ret))
            }
        } else {
            fmt.Println(err)
        }
    
    }
    
    func main() {
        http.HandleFunc("/", index)
        http.HandleFunc("/test/", test)
    
        if err := http.ListenAndServe("192.168.2.231:9090", nil); err != nil {
            log.Fatal("ListenAndServe", err)
        }
    }
    
    

    相关文章

      网友评论

        本文标题:GO: web服务器

        本文链接:https://www.haomeiwen.com/subject/wdnmvxtx.html