发请求,接收接送,并解析
package main import ( "fmt" "net/http" "io/ioutil" "net/url" "encoding/json" "os" ) type Student struct { Name string Age int Guake bool Classes []string Price float32 } func (s *Student) ShowStu() { fmt.Println("show Student :") fmt.Println("\tName\t:", s.Name) fmt.Println("\tAge\t:", s.Age) fmt.Println("\tGuake\t:", s.Guake) fmt.Println("\tPrice\t:", s.Price) fmt.Printf("\tClasses\t: ") for _, a := range s.Classes { fmt.Printf("%s ", a) } fmt.Println("") } type multitypeTest struct { One string `json:"one"` Two string `json:"two"` } func (s *multitypeTest) Showmul() { fmt.Println("show Student :") fmt.Println("\tName\t:", s.One) fmt.Println("\tAge\t:", s.Two) } func IndexHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "hello world") } func main() { //jsonTest() httpGet() } func httpPostForm() { resp, err := http.PostForm("", url.Values{"key": {"Value"}, "id": {"123"}}) if err != nil { // handle error } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { // handle error } fmt.Println(string(body)) } func httpGet() { resp, err := http.Get("https://X.rong360.com/XXX/XXX") CheckError(err) defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) CheckError(err) fmt.Println(string(body)) //f1 := &multitypeTest{ // One:"a", // Two:"b", // } //f1.Showmul() //fjson1, err := json.Marshal(f1) //fmt.Println(string(fjson1)) CheckError(err) f2 := &multitypeTest{} err = json.Unmarshal([]byte(body), &f2) CheckError(err) f2.Showmul() } func jsonTest() { //解析固定结构的json st := &Student{ "Xiao Ming", 16, true, []string{"Math", "English", "Chinese"}, 9.99, } st1, err := json.Marshal(st) fmt.Println(string(st1)) CheckError(err) stb := &Student{} err = json.Unmarshal([]byte(st1), &stb) stb.ShowStu() // //b := []byte(`{1:"Wednesday",2:6,3:["Gomez","Morticia"]}`) ////解析未知结构的json //var f interface{} //err = json.Unmarshal(b, &f) //CheckError(err) //这是f里面存储的是一个键值对的map //f = map[string]interface{}{ // "Name": "Wednesday", // "Age": 6, // "Parents": []interface{}{ // "Gomez", // "Morticia", // }, //} //m := f.(map[interface{}]interface{}) //for k, v := range m { // switch vv := v.(type) { // case string: // fmt.Println(k, "is string", vv) // case int: // fmt.Println(k, "is int", vv) // case float64: // fmt.Println(k, "is float64", vv) // case []interface{}: // fmt.Println(k, "is an array:") // for i, u := range vv { // fmt.Println(i, u) // } // default: // fmt.Println(k, "is of a type I don't know how to handle") // } //} } func CheckError(err error) { if err != nil { fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error()) os.Exit(1) } }
有疑问加站长微信联系(非本文作者)