package main
import (
"fmt"
"log"
"net/http"
)
/*NewBaseJsonBean用于创建一个struct对象:*/
type BaseJsonBean struct {
Code int `json:"code"`
Data interface{} `json:"data"`
Message string `json:"message"`
}
func NewBaseJsonBean() *BaseJsonBean {
return &BaseJsonBean{}
}
func main() {
http.HandleFunc("/", hander)
err := http.ListenAndServe("localhost:9090", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
func hander(w http.ResponseWriter, r *http.Request){
//path := r.URL.Path
//fmt.Fprintf(w, "Hello world")
//fmt.Println("path:", path)
//fmt.Println("method:", r.Method)
//fmt.Println("username:", r.PostFormValue("username"))
/* 返回json格式的数据 直接解析POST
curl -d "username=aa&passwd=123" 127.0.0.1:9090 */
r.ParseForm()
//r.FormValue("username")//这样使用也没毛病
//r.FormValue("password")//这样使用也没毛病
param_username, found1 := r.Form["username"]
param_password, found2 := r.Form["password"]
fmt.Println("username:", param_username)
fmt.Println("password:", param_password)
if !(found1 && found2) {
fmt.Fprint(w, "请勿非法访问")
return
}
result := NewBaseJsonBean()
username := param_username[0]
password := param_password[0]
if username == "aa" && password == "123" {
result.Code = 100
result.Message = "登录成功"
} else {
result.Code = 101
result.Message = "用户名或密码不正确"
}
//向客户端返回JSON数据
bytes, _ := json.Marshal(result)
fmt.Fprint(w, string(bytes))
}
/* 直接解析POST curl -d '{"username":"aa"}' 127.0.0.1:9090 */
var mapData map[string]interface{}
body, _ := ioutil.ReadAll(r.Body)
json.Unmarshal(body, &mapData)
domain := mapData["domain"].(string)//通过.(string)转换成string类型
log.Println(domain)
if len(domain) != 0 {
log.Println("输入合法")
} else {
log.Println("输入不合法")
}
golang服务端解析客户端发来的post数据
于 2019-10-31 10:29:07 首次发布