1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
| 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()) } }
|