Go 学习笔记(78)— Go 标准库 net/http 创建服务端(接收 GET、POST 请求)
生活随笔
收集整理的這篇文章主要介紹了
Go 学习笔记(78)— Go 标准库 net/http 创建服务端(接收 GET、POST 请求)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
使用 net/http 標準庫創建一個 http 的 restful api 的服務端,用來處理 GET、POST 等請求。
源代碼如下:
package mainimport ("encoding/json""fmt""net""net/http""strconv""time"
)type Contact struct {Home string `json:"home"`Cell string `json:"cell"`
}type Student struct {Name string `json:"name"`Year string `json:"year"`Contact Contact `json:"contact"`
}// 任務的HTTP接口
type ApiServer struct {httpServer *http.Server
}// HTTP接口應答
type Response struct {Errno int `json:"errno"`Msg string `json:"msg"`Data interface{} `json:"data"`
}// 構造一個響應
func BuildResponse(errno int, msg string, data interface{}) ([]byte, error) {// 1, 定義一個responseresponse := &Response{Errno: errno,Msg: msg,Data: data,}// 2, 序列化jsonresp, err := json.Marshal(response)return resp, err
}func saveFunction(resp http.ResponseWriter, req *http.Request) {// 1, 解析 POST 表單err := req.ParseForm()if err != nil {fmt.Printf("ParseForm error: %s\n", err)}// 獲取表單中所有字段內容fmt.Printf("req.PostForm is %v", req.PostForm)// 2, 取表單中的 name 字段name := req.PostForm.Get("name")fmt.Printf("name: %s\n", name)contactInfo := req.PostForm.Get("contact")fmt.Printf("contactInfo: %s\n", contactInfo)// 3, 反序列化jobvar contact Contacterr = json.Unmarshal([]byte(contactInfo), &contact)fmt.Printf("contact: %s\n", contact)if err != nil {fmt.Printf("Unmarshal error: %s\n", err)}// 4, 保存到數據庫// saveToDB()// 5, 返回正常應答 ({"errno": 0, "msg": "", "data": {....}})bytes, err := BuildResponse(0, "success", contact)if err == nil {resp.Write(bytes)}
}func listFunction(resp http.ResponseWriter, req *http.Request) {// 1. 解析GET參數err := req.ParseForm()if err != nil {fmt.Printf("ParseForm error: %s\n", err)}// 2. 獲取請求參數 /api/list?name=wohuname := req.Form.Get("name")fmt.Printf("name: %s\n", name)// 3. 從數據庫中讀取對應的字段值后顯示// ret := queryDB()// 4. 返回正常應答 ({"errno": 0, "msg": "", "data": {....}})bytes, err := BuildResponse(0, "success", name)if err == nil {resp.Write(bytes)}
}// 初始化服務
func InitApiServer() (err error) {// 配置路由mux := http.NewServeMux()mux.HandleFunc("/api/save", saveFunction)// mux.HandleFunc("/api/del", delFunction)// mux.HandleFunc("/api/update", updateFunction)mux.HandleFunc("/api/list", listFunction)// 啟動TCP監聽listener, err := net.Listen("tcp", ":"+strconv.Itoa(8070))if err != nil {return}// 創建一個HTTP服務httpServer := &http.Server{ReadTimeout: 100 * time.Millisecond,WriteTimeout: 100 * time.Millisecond,Handler: mux,}// 啟動了服務端go httpServer.Serve(listener)return
}func main() {InitApiServer()// 正常退出for {time.Sleep(1 * time.Second)}
}
然后使用 Postman 工具發送 GET、POST 請求:
總結
以上是生活随笔為你收集整理的Go 学习笔记(78)— Go 标准库 net/http 创建服务端(接收 GET、POST 请求)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2022-2028年中国橡胶漆产业发展动
- 下一篇: 2021-2027年中国氟磷腈橡胶行业发