RESTful API This thing doesn't have to say much, with go to make a very simple example:
The server returns JSON when it is invoked,
The client resolves to get the relevant JSON information.
Server Source:
Package main//Simple JSON Restful API demo (server side)//author:xiong Chuan liang//date:2015-2-28import ("Encoding/json" "FMT" "net/ http "" Time ") type Item struct {Seq intresult map[string]int}type Message struct {Dept stringsubject stringtime< C2/>int64detail []item}func Getjson () ([]byte, error) {pass: = Make (Map[string]int) pass["x"] = 50pass["C"] = 60item1 : = item{100, Pass}reject: = Make (Map[string]int) reject["l"] = 11reject["D"] = 20item2: = item{200, Reject}detail: = []Item {item1, Item2}m: = message{"IT", "KPI", time. Now (). Unix (), Detail}return json. Marshalindent (M, "", "")}func Handler (w http. Responsewriter, R *http. Request) {resp, err: = Getjson () if err! = Nil {panic (err)}fmt. fprintf (W, String (RESP))}func Main () {http. Handlefunc ("/", handler) HTTP. Listenandserve ("localhost:8085", Nil)}
After the server source code is running, you can perform the following effect in the browser:
Indicates that the return is normal. Then use go to write a calling program under test:
Package main//Simple JSON Restful API demo (call side)//author:xiong Chuan liang//date:2015-2-28import ("Encoding/json" "FMT" "io/ Ioutil "" Net/http "" Time ") type Item struct {Seq intresult map[string]int}type Message struct {Dept Stringsubject stringtime int64detail []item}func main () {URL: = "http://localhost:8085" ret, err: = http. Get (URL) if err! = Nil {panic (err)}defer ret. Body.close () body, err: = Ioutil. ReadAll (ret. Body) If err! = Nil {panic (err)}var msg messageerr = json. Unmarshal (body, &msg) if err! = Nil {panic (err)}strtime: = time. Unix (Msg. Time, 0). Format ("2006-01-02 15:04:05") fmt. Println ("Dept:", Msg. Dept) fmt. Println ("Subject:", Msg. Subject) fmt. Println ("Time:", Strtime, "\ n", Msg.) Detail)}/*//Run Result: dept:itsubject:kpitime:2015-02-28 16:43:11 [{map[c:60 x:50]} {$ map[d:20 l:11]}]*/
As you can see from the running results, the relevant JSON information is correctly obtained.
MAIL: [Email protected]
blog:http://blog.csdn.net/xcl168
Simple RESTful API Example (Golang)