zoukankan      html  css  js  c++  java
  • golang API

    1.server端程序

    package main
    
    //简单的JSON Restful API演示(服务端)
    //author: Xiong Chuan Liang
    //date: 2015-2-28
    
    import (
    	"encoding/json"
    	"fmt"
    	"net/http"
    	"time"
    )
    
    type Item struct {
    	Seq    int
    	Result map[string]int
    }
    
    type Message struct {
    	Dept    string
    	Subject string
    	Time    int64
    	Detail  []Item
    }
    
    func getJson() ([]byte, error) {
    	pass := make(map[string]int)
    	pass["x"] = 50
    	pass["c"] = 60
    	item1 := Item{100, pass}
    
    	reject := make(map[string]int)
    	reject["l"] = 11
    	reject["d"] = 20
    	item2 := 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)
    }
    

      2.client端程序

    package main
    
    //简单的JSON Restful API演示(调用端)
    //author: Xiong Chuan Liang
    //date: 2015-2-28
    
    import (
    	"encoding/json"
    	"fmt"
    	"io/ioutil"
    	"net/http"
    	"time"
    )
    
    type Item struct {
    	Seq    int
    	Result map[string]int
    }
    
    type Message struct {
    	Dept    string
    	Subject string
    	Time    int64
    	Detail  []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 Message
    	err = 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, "
    ", msg.Detail)
    }
    
    /*
    //运行结果:
    
    Dept: IT
    Subject: KPI
    Time: 2015-02-28 16:43:11
     [{100 map[c:60 x:50]} {200 map[d:20 l:11]}]
    
    */
    

      

  • 相关阅读:
    db2中的常用命令及使用方法
    互联网服务应用协议设计
    Zookeeper整理(一)- 写操作产生事件,写操作与Watcher对应关系
    实现自己的连接池(一)
    SMP、NUMA、MPP体系结构介绍
    随手备忘 ubuntu12.04 lts 安装gcc 4.8
    认真体会 结构体中的零长度数组
    由内存池实现总结内存对齐问题
    认真理解 oom killer 备忘
    仔细体会 epoll中的et lt模式
  • 原文地址:https://www.cnblogs.com/peterinblog/p/7874109.html
Copyright © 2011-2022 走看看