当前位置:网站首页>What is the development of the spot options contract exchange system丨Detailed technology for the development of the spot options contract exchange system
What is the development of the spot options contract exchange system丨Detailed technology for the development of the spot options contract exchange system
2022-08-07 16:46:00 【I357O98O7I8】
通过mux定义了两个Handler,URL都是/,但是对应的Method是不一样的.
GET方法通过handleGetBlockchain函数实现,Information for obtaining the blockchain.
func handleGetBlockchain(w http.ResponseWriter, r *http.Request) {
bytes, err := json.MarshalIndent(Blockchain, "", " ")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
io.WriteString(w, string(bytes))
}Blockchain是一个[]Block,handleGetBlockchain函数的作用是把Blockchain格式化为JSON字符串,然后显示出来.io.WriteString是一个很好用的函数,可以往Writerwrite a string in it.更多参考 Go语言实战笔记(十九)| Go Writer 和 Reader
'POST'方法通过handleWriteBlock函数实现,Used to simulate the generation of chunks.
func handleWriteBlock(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
//使用了一个Mesage结构体,more convenient storageBPM
var msg Message
//Receive the requested data information,类似{"BPM":60}这样的格式
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&msg); err != nil {
respondWithJSON(w, r, http.StatusBadRequest, r.Body)
return
}
defer r.Body.Close()
//控制并发,生成区块链,并且校验
mutex.Lock()
prevBlock := Blockchain[len(Blockchain)-1]
newBlock := generateBlock(prevBlock, msg.BPM)
//Check the blockchain
if isBlockValid(newBlock, prevBlock) {
Blockchain = append(Blockchain, newBlock)
spew.Dump(Blockchain)
}
mutex.Unlock()
//Returns new block information
respondWithJSON(w, r, http.StatusCreated, newBlock)
}I have commented the above code,便于理解.主要是通过POST发送一个{"BPM":60}格式的BODYto add blocks,如果格式正确,Then a block is generated for verification,If qualified, it will be added to the block;如果格式不对,那么返回错误信息.
The lock used to control concurrency can refer toGo语言实战笔记(十七)| Go 读写锁
There is one in this methodMessage结构体,Mainly for ease of operation.
// Message takes incoming JSON payload for writing heart rate
type Message struct {
BPM int
}返回的JSON信息,Also extracted as a functionrespondWithJSON,便于公用.
func respondWithJSON(w http.ResponseWriter, r *http.Request, code int, payload interface{}) {
response, err := json.MarshalIndent(payload, "", " ")
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("HTTP 500: Internal Server Error"))
return
}
w.WriteHeader(code)
w.Write(response)
}好了,快完成了,以上Web的Handler已经好了,Now we're going to start oursWeb服务了.
// web server
func run() error {
mux := makeMuxRouter()
//Read the listening port from the configuration file
httpPort := os.Getenv("PORT")
log.Println("HTTP Server Listening on port :", httpPort)
s := &http.Server{
Addr: ":" + httpPort,
Handler: mux,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
if err := s.ListenAndServe(); err != nil {
return err
}
return nil
}和原生的http.Server基本一样,应该比较好理解.mux其实也是一个Handler,这就是整个Handler处理链.Now we're one short of itmainThe main function to start our entire program.
//控制并发的锁
var mutex = &sync.Mutex{}
func main() {
//加载env配置文件
err := godotenv.Load()
if err != nil {
log.Fatal(err)
}
//开启一个goroutineGenerate a genesis block
go func() {
t := time.Now()
genesisBlock := Block{}
genesisBlock = Block{0, t.String(), 0, calculateHash(genesisBlock), ""}
spew.Dump(genesisBlock)
mutex.Lock()
Blockchain = append(Blockchain, genesisBlock)
mutex.Unlock()
}()
log.Fatal(run())
}整个mainThe function is not too complicated,主要就是加载env配置文件,开启一个goThe coroutine generates a genesis block and adds it to the first position in the blockchain,然后就是通过run函数启动Web服务.
Every blockchain has a genesis block,That is the first block.With the first block we can add the second,第三个,第N个区块.The genesis block is the first block,所以它是没有PrevHash的.
边栏推荐
猜你喜欢

8. 动态 WEB 开发核心-Servlet

【kali-权限提升】(4.1)假冒令牌攻击、本地提权:流程

1325_FreeRTOS队列发送函数的实现分析

Byte's favorite puzzle questions, how many do you know?

【数学建模】matlab向量(数组)

2.10 - 存储管理 2.11 - 页式存储 2.12 - 段式存储 2.13 - 段页式存储

Simple Web Production Final Assignment – The Movie Titanic (4 pages)

云/移动端媒体处理技术分享

Analysis of various related architectures of MCU
![[Thesis translation and interpretation (1)] Mitigating Confounding Bias in Recommendation via Information Bottleneck](/img/7e/41b4e4d616ebc81d93a4328b897790.png)
[Thesis translation and interpretation (1)] Mitigating Confounding Bias in Recommendation via Information Bottleneck
随机推荐
1325_FreeRTOS队列发送函数的实现分析
基于Web的商城后台管理系统的设计与实现
ceph集群
【解决】Can‘t add ‘UniversalAdditionalCameraData‘ to SceneCamera because a ‘UniversalAdditionalCamera...
Oracle commonly used numeric functions
R语言ggplot2可视化:使用ggpubr包的ggerrorplot函数可视化水平误差线(orientation)、设置add参数显示均值、error.plot参数显示误差条
HDU 1712:ACboy needs your help ← 分组背包问题
Why are test/dev programmers paid so much?
如何使用 saplink 安装其他网站上提供的 ABAP 程序试读版
MySQL5.7 installation and configuration tutorial (graphics and text super detailed version)
研扬Jetson NX镜像备份和恢复
LeetCode_796_Rotate String
超级基础的面试题总结
Chapter 13 _ Transaction Basics
系统设计题面试八股文背诵版
pytorch save training log
Unity Webgl发布的一些注意的点
熟练使用几个重要的内置函数
yolov5使用GPU
初识微信小程序开发