go語言web系列2 json
阿新 • • 發佈:2019-02-03
package main import ( "net/http" "fmt" "net/url" "io/ioutil" "encoding/json" "log" "strconv" ) type Hero struct { Name string Skill []Action Position int } type Action struct { Id int Desc string } // request: localhost:9090/getHeroInfo?id=1 // response: {"Name":"SF","Skill":[{"Id":1,"Desc":"影壓"},{"Id":2,"Desc":"收魂"},{"Id":3,"Desc":"減甲"},{"Id":4,"Desc":"輓歌"}],"Position":1} func getHeroInfo(w http.ResponseWriter, r *http.Request) { queryForm, err := url.ParseQuery(r.URL.RawQuery) id, err := strconv.Atoi(queryForm["id"][0]) if err != nil { fmt.Println("字串轉數字失敗") } hero1 := Hero{ Name: "SF", Skill: []Action{ {Id: 1, Desc: "影壓"}, {Id: 2, Desc: "收魂"}, {Id: 3, Desc: "減甲"}, {Id: 4, Desc: "輓歌"}, }, Position: id, } hero1_info, err := json.Marshal(hero1) if err != nil { log.Fatal("ListenAndServe: ", err) } fmt.Fprintln(w, string(hero1_info)) } // request: {"Name":"SF","Skill":[{"Id":1,"Desc":"影壓"},{"Id":2,"Desc":"收魂"},{"Id":3,"Desc":"減甲"},{"Id":4,"Desc":"輓歌"}],"Position":1} // response: {kaer [{1 天火} {2 冰牆} {3 吹風} {4 隕石}] 2} func changeHeroInfo(w http.ResponseWriter, r *http.Request) { //var user map[string]interface{} var hero2 Hero body, _ := ioutil.ReadAll(r.Body) json.Unmarshal(body, &hero2) hero2.Name = "kaer" hero2.Skill = []Action{ {Id: 1, Desc: "天火"}, {Id: 2, Desc: "冰牆"}, {Id: 3, Desc: "吹風"}, {Id: 4, Desc: "隕石"}, } hero2.Position = 2 fmt.Fprintln(w, hero2) } func main() { http.HandleFunc("/getHeroInfo", getHeroInfo) http.HandleFunc("/changeHeroInfo", changeHeroInfo) err := http.ListenAndServe(":9090", nil) if err != nil { log.Fatal("ListenAndServe: ", err) } }