網站首頁 編程語言 正文
Http Server 代碼
go.mod:
module goStudy1 go 1.17
main.go:
package main import ( "fmt" "os" "strconv" //"github.com/thinkeridea/go-extend/exnet" "io" "log" "net/http" "strings" ) /* 編寫一個 HTTP 服務器,4個功能: 1,接收客戶端 request,并將 request 中帶的 header 寫入 response header 2,讀取當前系統的環境變量中的 VERSION 配置,并寫入 response header 3,Server 端記錄訪問日志包括客戶端 IP,HTTP 返回碼,輸出到 server 端的標準輸出 4,當訪問 localhost/healthz 時,應返回 200 */ // Main方法入口 func main() { println("環境正常") // 功能1 http.HandleFunc("/requestAndResponse", requestAndResponse) // 功能2 http.HandleFunc("/getVersion", getVersion) // 功能3 http.HandleFunc("/ipAndStatus", ipAndStatus) //注冊接口句柄 // 功能4 http.HandleFunc("/healthz", healthz) //注冊接口句柄 err := http.ListenAndServe(":81", nil) //監聽空句柄,80端口被占用,使用81端口 if nil != err { log.Fatal(err) //顯示錯誤日志 } } // 功能1,接收請求及響應 func requestAndResponse(response http.ResponseWriter, request *http.Request) { println("調用requestAndResponse接口") headers := request.Header //header是Map類型的數據 println("傳入的hander:") for header := range headers { //value是[]string //println("header的key:" + header) values := headers[header] for index, _ := range values { values[index] = strings.TrimSpace(values[index]) //println("index=" + strconv.Itoa(index)) //println("header的value:" + values[index]) } //valueString := strings.Join(values, "") //println("header的value:" + valueString) println(header + "=" + strings.Join(values, ",")) //打印request的header的k=v response.Header().Set(header, strings.Join(values, ",")) // 遍歷寫入response的Header //println() } fmt.Fprintln(response, "Header全部數據:", headers) io.WriteString(response, "succeed") } // 功能2,獲取環境變量的version func getVersion(response http.ResponseWriter, request *http.Request) { println("調用getVersion接口") envStr := os.Getenv("VERSION") //envStr := os.Getenv("HADOOP_HOME") //println("系統環境變量:" + envStr) //可以看到 C:\soft\hadoop-3.3.1 Win10需要重啟電腦才能生效 response.Header().Set("VERSION", envStr) io.WriteString(response, "succeed") } // 功能3,輸出IP與返回碼 func ipAndStatus(response http.ResponseWriter, request *http.Request) { println("調用ipAndStatus接口") form := request.RemoteAddr println("Client->ip:port=" + form) //虛擬機是橋接模式。使用postman返回的全部是127.0.0.1 用手機打開網站192.168.1.139:81/ipAndStatus可以看到新IP ipStr := strings.Split(form, ":") println("Client->ip=" + ipStr[0]) //打印ip // 獲取http響應碼 //response.WriteHeader(301) //手動設置響應碼,默認200 //response.WriteHeader(http.StatusOK)//由于默認是調用這個,∴返回碼都是這個200【server.go有源碼】 println("Client->response code=" + strconv.Itoa(http.StatusOK)) //println("response code->:" + code) io.WriteString(response, "succeed") } // 功能4,連通性測試接口 func healthz(response http.ResponseWriter, request *http.Request) { println("調用healthz接口") response.WriteHeader(200) //設置返回碼200 //response.WriteHeader(http.StatusOK)//默認會調用這個方法,默認就是200【server.go有源碼】 io.WriteString(response, "succeed") }
由于80端口被占用,使用了81端口。
調試
由于Linux虛擬機沒有安裝go環境,只有windows有go環境,使用goland開發后,用postman調試。
功能1
網站:http://127.0.0.1:81/requestAndResponse
POST的request中額外配置了 k2=v1 。Send后可以看到:
Response中出現了手動新增的請求頭及其它默認的請求頭。【原始的response只有3對kv結果,已經遍歷添加成功】。說明成功寫入。
功能2
由于Windows需要重啟才能刷新環境變量,故:
//envStr := os.Getenv("VERSION") envStr := os.Getenv("HADOOP_HOME")
測試時,此處讀取已經存在的環境變量,原理是一致的。
網站:http://127.0.0.1:81/getVersion
說明Go可以讀取到環境變量的值,并且寫入response的headers。
功能3
網站:http://127.0.0.1:81/ipAndStatus
分別用postman、手機請求這個網站【手機請求時需要和PC在同一個路由,將網站IP更換為PC的IP才可以訪問】,goland中顯示:
環境正常
調用getVersion接口
調用ipAndStatus接口
Client->ip:port=127.0.0.1:59595
Client->ip=127.0.0.1
Client->response code=200
調用ipAndStatus接口
Client->ip:port=192.168.1.138:37548
Client->ip=192.168.1.138
Client->response code=200
顯然讀取到了client的IP。由于server.go中有寫:
// WriteHeader sends an HTTP response header with the provided // status code. // // If WriteHeader is not called explicitly, the first call to Write // will trigger an implicit WriteHeader(http.StatusOK). // Thus explicit calls to WriteHeader are mainly used to // send error codes. // // The provided code must be a valid HTTP 1xx-5xx status code. // Only one header may be written. Go does not currently // support sending user-defined 1xx informational headers, // with the exception of 100-continue response header that the // Server sends automatically when the Request.Body is read. WriteHeader(statusCode int)
默認的響應頭就是取返回值為200,不設置就是按照默認的200來返回,故此處的響應碼為200。
由于響應體引用的請求體并不包含返回碼,如果直接從響應體的請求中拿返回碼【request.Response.StatusCode】,會報內存錯誤及空指針的panic。
功能4
網址:http://127.0.0.1:81/healthz
使用postman調用接口,可以看到:
默認的響應體的響應頭的返回碼就是200。且返回值3個。
可以看出,Go相比Java還是很簡潔的。
原文鏈接:https://blog.csdn.net/qq_41990268/article/details/124334227
相關推薦
- 2022-04-19 Android線性布局與相對布局的實現_Android
- 2022-11-06 pytorch簡單實現神經網絡功能_python
- 2022-10-26 Pytorch中torch.stack()函數的深入解析_python
- 2022-06-01 Android中的Coroutine協程原理解析_Android
- 2022-05-20 python?特有語法推導式的基本使用_python
- 2022-04-30 C語言實現考勤管理系統_C 語言
- 2022-11-05 Kotlin數據容器深入講解_Android
- 2022-12-13 OpenCV視頻流C++多線程處理方法詳細分析_C 語言
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支