round one,我们来点简单的,搭建一个简单的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() }
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) }
|
再来看一下接收参数与输出:
func sayHello(w http.ResponseWriter, r *http.Request) { query := r.URL.Query()
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 }
http.Error(w, "you lost???", http.StatusNotFound) }
|
我们运行起来看下效果:
404效果
hello
首页
超时
这样就完成了一个简单的http server,是不是很简单呢?