GO

GO: web服务器

2017-11-20  本文已影响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)
    }
}

上一篇下一篇

猜你喜欢

热点阅读