网上抄的,顺便整合了一下。
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
)
// Get :接收GET请求
func Get(writer http.ResponseWriter , request *http.Request) {
query := request.URL.Query()
// 第一种方式
// id := query["id"][0]
// 第二种方式
id := query.Get("id")
name:= query.Get("name")
if id == `` {
fmt.Fprintf(writer,`id missing`)
} else if name == `` {
fmt.Fprintf(writer,`name missing`)
}else {
log.Printf("GET: id=%s\n", id)
log.Printf("GET: name=%s\n", name)
//fmt.Fprintf(writer, `{"code":0}`)
fmt.Fprintf(writer, `Success!`)
}
}
// Post :接收application/x-www-form-urlencoded类型的POST请求
func Post(writer http.ResponseWriter, request *http.Request) {
err := request.ParseForm()
if err != nil {
return
}
// 第一种方式
// username := request.Form["username"][0]
// password := request.Form["password"][0]
// 第二种方式
username := request.Form.Get("username")
password := request.Form.Get("password")
if username == ``{
fmt.Fprintf(writer,`username missing`)
} else if password == ``{
fmt.Fprintf(writer,`password missing`)
} else {
fmt.Printf("POST form-urlencoded: username=%s, password=%s\n", username, password)
//fmt.Fprintf(writer, `{"code":0}`)
fmt.Fprintf(writer,`Success!`)
}
}
//处理 application/json 请求
//思路是这样的:
//1.先将 json 转成 struct。
//2.然后 json.Unmarshal() 即可。
//AutoGenerated 结构体
type AutoGenerated struct {
Resultcode string `json:"resultcode"`
Reason string `json:"reason"`
Result struct {
Province string `json:"province"`
City string `json:"city"`
Areacode string `json:"areacode"`
Zip string `json:"zip"`
Company string `json:"company"`
Card string `json:"card"`
} `json:"result"`
}
// PostJson : 处理 application/json 请求
func PostJson(w http.ResponseWriter, r *http.Request ) {
body ,err := ioutil.ReadAll(r.Body)
if err != nil {
log.Println( err)
}
log.Printf("%s",body)
var data AutoGenerated
json.Unmarshal([]byte(body),&data)
//Json结构返回
json,_ := json.Marshal(data)
w.Write(json)
}
func main() {
http.HandleFunc("/get", Get)
http.HandleFunc("/post", Post)
http.HandleFunc("/PostJson",PostJson)
log.Println("Running at port 9999 ...")
err := http.ListenAndServe(":9999", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err.Error())
}
}