5.1. 搭建http server
无水印图片找不到嘞,文中图片来自知乎自己以前的账号,现在是开源到。
目标:#
- 路由 hello 接收参数并获取到输出 json 数据
- 自定义 404
- 处理超时页面
使用到的库:#
- net/http
- time
- encoding/json
我们先搭建起来 server:
package main
import (
"net/http"
)
func main() {
srv := http.Server{
Addr: ":8080",
Handler: http.HandlerFunc(defaultHttp),
}
srv.ListenAndServe()
}
// 默认http处理
func defaultHttp(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("wow"))
}
运行就可以跑起来了。
我们再来定义下 json 输出格式。
// 自定义返回
type JsonRes struct {
Code int `json:"code"`
Data interface{} `json:"data"`
Msg string `json:"msg"`
TimeStamp int64 `json:"timestmap"`
}
func apiResult(w http.ResponseWriter, code int, data interface{}, msg string) {
body, _ := json.Marshal(JsonRes{
Code: code,
Data: data,
Msg: msg,
// 获取时间戳
TimeStamp: time.Now().Unix(),
})
w.Write(body)
}
再来看一下接收参数与输出:
// 处理hello,并接收参数输出json
func sayHello(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
// 第一种方式,但是没有name参数会报错
// name := query["name"][0]
// 第二种方式
name := query.Get("name")
apiResult(w, 0, name+" say "+r.PostFormValue("some"), "success")
}
超时处理:
Handler: http.TimeoutHandler(http.HandlerFunc(defaultHttp), 2*time.Second, "Timeout!!!")
404:
http.Error(w, "you lost???", http.StatusNotFound)
最后加入路由处理:
func defaultHttp(w http.ResponseWriter, r *http.Request) {
path, httpMethod := r.URL.Path, r.Method
if path == "/" {
w.Write([]byte("index"))
return
}
if path == "/hello" && httpMethod == "POST" {
sayHello(w, r)
return
}
if path == "/sleep" {
// 模拟一下业务处理超时
time.Sleep(4*time.Second)
return
}
if path == "/path" {
w.Write([]byte("path:"+path+", method:"+httpMethod))
return
}
// 自定义404
http.Error(w, "you lost???", http.StatusNotFound)
}
我们运行起来看下效果:
404 效果
hello
首页
超时
这样就完成了一个简单的 http server,是不是很简单呢?
关注和赞赏都是对笔者最大的支持
推荐文章: