go原生http服务
195字小于1分钟
2025-02-04
在实际项目中使用原生go http库那会非常不方便
主要体现在
- 参数需要解析与验证(是否json数据)
- 路由不太清晰
- 响应处理比较原始,例如需要手动处理响应json
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
)
type Respose struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data any `json:"data"`
}
func Index(writer http.ResponseWriter, request *http.Request) {
fmt.Println("请求方法", request.Method, "请求url", request.URL.String())
if request.Method != "Get" {
byteData, _ := io.ReadAll(request.Body)
fmt.Println("请求体", string(byteData))
}
fmt.Println("请求头", request.Header)
//writer.Write([]byte("hello world")) //响应内容
r := Respose{Code: 200, Msg: "成功", Data: map[string]string{}}
byteData, _ := json.Marshal(r)
writer.Write(byteData) //响应json
}
func main() {
http.HandleFunc("/index", Index)
fmt.Println("http server running 127.0.0.1:8081")
//启动一个http服务 0.0.0.0 可省略
http.ListenAndServe("0.0.0.0:8081", nil)
}