Go語言實戰 : API服務器 (3) 服務器雛形

簡單API服務器功能

實現外部請求對API 服務器健康檢查和狀態查詢,返回響應結果

1.API服務器的狀態監測

以內存狀態檢測為例,獲取當前服務器的健康狀況、服務器硬盤、CPU 和內存使用量

func RAMCheck(c *gin.Context) {u, _ := mem.VirtualMemory()//獲取當前內存占用量usedMB := int(u.Used) / MBusedGB := int(u.Used) / GBtotalMB := int(u.Total) / MBtotalGB := int(u.Total) / GBusedPercent := int(u.UsedPercent)status := http.StatusOKtext := "OK"//根據當前內存狀態,返回健康信息if usedPercent >= 95 {status = http.StatusInternalServerErrortext = "CRITICAL"} else if usedPercent >= 90 {status = http.StatusTooManyRequeststext = "WARNING"}message := fmt.Sprintf("%s - Free space: %dMB (%dGB) / %dMB (%dGB) | Used: %d%%", text, usedMB, usedGB, totalMB, totalGB, usedPercent)c.String(status, "\n"+message)
}

2.加載路由

該代碼塊定義了一個叫 sd 的分組,在該分組下注冊了 /health、/disk、/cpu、/ram HTTP 路徑,分別路由到 sd.HealthCheck、sd.DiskCheck、sd.CPUCheck、sd.RAMCheck 函數。sd 分組主要用來檢查 API Server 的狀態:健康狀況、服務器硬盤、CPU 和內存使用量

// Load loads the middlewares, routes, handlers.
func Load(g *gin.Engine, mw ...gin.HandlerFunc) *gin.Engine {// Middlewares.//設置響應頭g.Use(gin.Recovery())g.Use(middleware.NoCache)g.Use(middleware.Options)g.Use(middleware.Secure)g.Use(mw...)// 404 Handler.//404設置g.NoRoute(func(c *gin.Context) {c.String(http.StatusNotFound, "The incorrect API route.")})// The health check handlerssvcd := g.Group("/sd"){svcd.GET("/health", sd.HealthCheck)svcd.GET("/disk", sd.DiskCheck)svcd.GET("/cpu", sd.CPUCheck)svcd.GET("/ram", sd.RAMCheck)}return g
}

3.程序入口

程序入口先進行路由的加載,隨后在 apiserver 中也添加自檢程序,在啟動 HTTP 端口前 go 一個 pingServer 協程,啟動 HTTP 端口后,該協程不斷地 ping /sd/health 路徑,如果失敗次數超過一定次數,則終止 HTTP 服務器進程。通過自檢可以最大程度地保證啟動后的 API 服務器處于健康狀態。

func main() {// Create the Gin engine.g := gin.New()middlewares := []gin.HandlerFunc{}// Routes.router.Load(// Cores.g,// Middlwares.middlewares...,)// Ping the server to make sure the router is working.go func() {if err := pingServer(); err != nil {log.Fatal("The router has no response, or it might took too long to start up.", err)}log.Print("The router has been deployed successfully.")}()log.Printf("Start to listening the incoming requests on http address: %s", ":8080")log.Printf(http.ListenAndServe(":8080", g).Error())
}// pingServer pings the http server to make sure the router is working.
func pingServer() error {for i := 0; i < 2; i++ {// Ping the server by sending a GET request to `/health`.resp, err := http.Get("http://127.0.0.1:8080" + "/sd/health")if err == nil && resp.StatusCode == 200 {return nil}// Sleep for a second to continue the next ping.log.Print("Waiting for the router, retry in 1 second.")time.Sleep(time.Second)}return errors.New("Cannot connect to the router.")
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/391351.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/391351.shtml
英文地址,請注明出處:http://en.pswp.cn/news/391351.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

TCP/IP協議-1

轉載資源&#xff0c;鏈接地址https://www.cnblogs.com/evablogs/p/6709707.html 轉載于:https://www.cnblogs.com/Chris-01/p/11474915.html

http://nancyfx.org + ASPNETCORE

商務產品servicestack&#xff1a; https://servicestack.net/ http://nancyfx.org ASPNETCORE http://nancyfx.org Drapper ORM精簡框架 https://github.com/StackExchange/Dapper Nancy 是一個輕量級用于構建基于 HTTP 的 Web 服務&#xff0c;基于 .NET 和 Mono 平…

使用r語言做garch模型_使用GARCH估計貨幣波動率

使用r語言做garch模型Asset prices have a high degree of stochastic trends inherent in the time series. In other words, price fluctuations are subject to a large degree of randomness, and therefore it is very difficult to forecast asset prices using traditio…

ARC下的內存泄漏

##ARC下的內存泄漏 ARC全稱叫 ARC(Automatic Reference Counting)。在編譯期間&#xff0c;編譯器會判斷對象的使用情況&#xff0c;并適當的加上retain和release&#xff0c;使得對象的內存被合理的管理。所以&#xff0c;從本質上說ARC和MRC在本質上是一樣的&#xff0c;都是…

python:校驗郵箱格式

# coding:utf-8import redef validateEmail(email):if re.match("^.\\(\\[?)[a-zA-Z0-9\\-\\.]\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", email) ! None:# if re.match("/^\w[a-z0-9]\.[a-z]{2,4}$/", email) ! None:print okreturn okelse:print failret…

cad2019字體_這些是2019年最有效的簡歷字體

cad2019字體When it comes to crafting the perfect resume to land your dream job, you probably think of just about everything but the font. But font is a key part of your first impression to recruiters and employers.當制作一份完美的簡歷來實現理想的工作時&…

Go語言實戰 : API服務器 (4) 配置文件讀取及連接數據庫

讀取配置文件 1. 主函數中增加配置初始化入口 先導入viper包 import (..."github.com/spf13/pflag""github.com/spf13/viper""log")在 main 函數中增加了 config.Init(*cfg) 調用&#xff0c;用來初始化配置&#xff0c;cfg 變量值從命令行 f…

方差偏差權衡_偏差偏差權衡:快速介紹

方差偏差權衡The bias-variance tradeoff is one of the most important but overlooked and misunderstood topics in ML. So, here we want to cover the topic in a simple and short way as possible.偏差-方差折衷是機器學習中最重要但被忽視和誤解的主題之一。 因此&…

win10 uwp 讓焦點在點擊在頁面空白處時回到textbox中

原文:win10 uwp 讓焦點在點擊在頁面空白處時回到textbox中在網上 有一個大神問我這樣的問題&#xff1a;在做UWP的項目&#xff0c;怎么能讓焦點在點擊在頁面空白處時回到textbox中&#xff1f; 雖然我的小伙伴認為他這是一個 xy 問題&#xff0c;但是我還是回答他這個問題。 首…

python:當文件中出現特定字符串時執行robot用例

#coding:utf-8 import os import datetime import timedef execute_rpt_db_full_effe_cainiao_city():flag Truewhile flag:# 判斷該文件是否存在# os.path.isfile("/home/ytospid/opt/docker/jsc_spider/jsc_spider/log/call_proc.log")# 存在則獲取昨天日期字符串…

MySQL分庫分表方案

1. MySQL分庫分表方案 1.1. 問題&#xff1a;1.2. 回答&#xff1a; 1.2.1. 最好的切分MySQL的方式就是&#xff1a;除非萬不得已&#xff0c;否則不要去干它。1.2.2. 你的SQL語句不再是聲明式的&#xff08;declarative&#xff09;1.2.3. 你招致了大量的網絡延時1.2.4. 你失去…

linux創建sudo用戶_Linux終極指南-創建Sudo用戶

linux創建sudo用戶sudo stands for either "superuser do" or "switch user do", and sudo users can execute commands with root/administrative permissions, even malicious ones. Be careful who you grant sudo permissions to – you are quite lit…

重學TCP協議(1) TCP/IP 網絡分層以及TCP協議概述

1. TCP/IP 網絡分層 TCP/IP協議模型&#xff08;Transmission Control Protocol/Internet Protocol&#xff09;&#xff0c;包含了一系列構成互聯網基礎的網絡協議&#xff0c;是Internet的核心協議&#xff0c;通過20多年的發展已日漸成熟&#xff0c;并被廣泛應用于局域網和…

分節符縮寫p_p值的縮寫是什么?

分節符縮寫pp是概率嗎&#xff1f; (Is p for probability?) Technically, p-value stands for probability value, but since all of statistics is all about dealing with probabilistic decision-making, that’s probably the least useful name we could give it.從技術…

Spring-----AOP-----事務

xml文件中&#xff1a; 手動處理事務&#xff1a; 設置數據源 <bean id"dataSource" class"com.mchange.v2.c3p0.ComboPooledDataSource"> <property name"driverClass" value"com.mysql.jdbc.Driver"></property…

[測試題]打地鼠

Description 小明聽說打地鼠是一件很好玩的游戲&#xff0c;于是他也開始打地鼠。地鼠只有一只&#xff0c;而且一共有N個洞&#xff0c;編號為1到N排成一排&#xff0c;兩邊是墻壁&#xff0c;小明當然不可能百分百打到&#xff0c;因為他不知道地鼠在哪個洞。小明只能在白天打…

在PHP服務器上使用JavaScript進行緩慢的Loris攻擊[及其預防措施!]

Forget the post for a minute, lets begin with what this title is about! This is a web security-based article which will get into the basics about how HTTP works. Well also look at a simple attack which exploits the way the HTTP protocol works.暫時忘掉這個帖…

三星為什么要賣芯片?手機干不過華為小米,半導體好掙錢!

據外媒DigiTimes報道&#xff0c;三星有意向其他手機廠商出售自家的Exynos芯片以擴大市場份額。知情人士透露&#xff0c;三星出售自家芯片旨在提高硅晶圓工廠的利用率&#xff0c;同時提高它們在全球手機處理器市場的份額&#xff0c;尤其是中端市場。 三星為什么要賣芯片&…

重學TCP協議(2) TCP 報文首部

1. TCP 報文首部 1.1 源端口和目標端口 每個TCP段都包含源端和目的端的端口號&#xff0c;用于尋找發端和收端應用進程。這兩個值加上IP首部中的源端IP地址和目的端IP地址唯一確定一個TCP連接 端口號分類 熟知端口號&#xff08;well-known port&#xff09;已登記的端口&am…

linux:vim中全選復制

全選&#xff08;高亮顯示&#xff09;&#xff1a;按esc后&#xff0c;然后ggvG或者ggVG 全部復制&#xff1a;按esc后&#xff0c;然后ggyG 全部刪除&#xff1a;按esc后&#xff0c;然后dG 解析&#xff1a; gg&#xff1a;是讓光標移到首行&#xff0c;在vim才有效&#xf…