golang原生http web进行简约封装
2020-04-24 本文已影响0人
百里江山
常规写法
一般我们用Golang原生写Web时,一般这样写
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
w.Write([]byte("ok"))
})
http.ListenAndServe(":8080", nil)
}
如果需要特定的GET,POST,PUT,DELETE处理. 我们需要这样写.
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
_, _ = w.Write([]byte(http.StatusText(http.StatusMethodNotAllowed)))
}
w.WriteHeader(http.StatusOK)
w.Write([]byte(http.StatusText(http.StatusOK)))
})
http.ListenAndServe(":8080", nil)
}
gorestful简约写法
对以上方法操作进行了封装.
- github.com/yezihack/gorestful
import (
"github.com/yezihack/gorestful"
"net/http"
)
func main() {
router := gorestful.New()
router.GET("/", Ping)
router.POST("/ping", Ping)
router.PUT("/ping", Ping)
router.PATCH("/ping", Ping)
router.DELETE("/ping", Ping)
router.HEAD("/ping", Ping)
router.CONNECT("/ping", Ping)
router.TRACE("/ping", Ping)
http.ListenAndServe(":8080", router)
}
func Ping(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte(http.StatusText(http.StatusOK)))
}
推荐
不过最后还是推荐使用httprouter, 大名顶顶的Gin Web框架就是使用这个的. 自己写的,纯属学习.