這篇“Go Http Server框架如何快速實(shí)現(xiàn)”文章的知識(shí)點(diǎn)大部分人都不太理解,所以小編給大家總結(jié)了以下內(nèi)容,內(nèi)容詳細(xì),步驟清晰,具有一定的借鑒價(jià)值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“Go Http Server框架如何快速實(shí)現(xiàn)”文章吧。
成都創(chuàng)新互聯(lián)堅(jiān)持“要么做到,要么別承諾”的工作理念,服務(wù)領(lǐng)域包括:網(wǎng)站制作、成都網(wǎng)站制作、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣等服務(wù),滿足客戶于互聯(lián)網(wǎng)時(shí)代的龍海網(wǎng)站設(shè)計(jì)、移動(dòng)媒體設(shè)計(jì)的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡(luò)建設(shè)合作伙伴!
在Go想使用 http server,最簡(jiǎn)單的方法是使用 http/net
err := http.ListenAndServe(":8080", nil)if err != nil {
panic(err.Error())}http.HandleFunc("/hello", func(writer http.ResponseWriter, request *http.Request) {
writer.Write([]byte("Hello"))})
定義 handle func
type HandlerFunc func(ResponseWriter, *Request)
標(biāo)準(zhǔn)庫(kù)的 http 服務(wù)器實(shí)現(xiàn)很簡(jiǎn)單,開啟一個(gè)端口,注冊(cè)一個(gè)實(shí)現(xiàn)HandlerFunc
的 handler
同時(shí)標(biāo)準(zhǔn)庫(kù)也提供了一個(gè)完全接管請(qǐng)求的方法
func main() {
err := http.ListenAndServe(":8080", &Engine{})
if err != nil {
panic(err.Error())
}}type Engine struct {}func (e *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/hello" {
w.Write([]byte("Hello"))
}}
定義 ServerHTTP
type Handler interface {
ServeHTTP(ResponseWriter, *Request)}
如果我們需要寫一個(gè) HTTP Server 框架,那么就需要實(shí)現(xiàn)這個(gè)方法,同時(shí) net/http 的輸入輸出流都不是很方便,我們也需要包裝,再加上一個(gè)簡(jiǎn)單的 Route,不要在 ServeHTTP 里面寫Path。
這里稍微總結(jié)一下
一個(gè)實(shí)現(xiàn) ServeHTTP 的Engine
一個(gè)包裝 HTTP 原始輸入輸出流的 Context
一個(gè)實(shí)現(xiàn)路由匹配的 Route
Route 這邊為了簡(jiǎn)單,使用Map做完全匹配
import (
"net/http")type Engine struct {
addr string
route map[string]handFunc}type Context struct {
w http.ResponseWriter
r *http.Request
handle handFunc}type handFunc func(ctx *Context) errorfunc NewServer(addr string) *Engine {
return &Engine{
addr: addr,
route: make(map[string]handFunc),
}}func (e *Engine) Run() {
err := http.ListenAndServe(e.addr, e)
if err != nil {
panic(err)
}}func (e *Engine) Get(path string, handle handFunc) {
e.route[path] = handle}func (e *Engine) handle(writer http.ResponseWriter, request *http.Request, handle handFunc) {
ctx := &Context{
w: writer,
r: request,
handle: handle,
}
ctx.Next()}func (e *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {
handleF := e.route[req.URL.Path]
e.handle(w, req, handleF)}func (c *Context) Next() error {
return c.handle(c)}func (c *Context) Write(s string) error {
_, err := c.w.Write([]byte(s))
return err}
我們寫一個(gè)Test驗(yàn)證一下我們的 Http Server
func TestHttp(t *testing.T) {
app := NewServer(":8080")
app.Get("/hello", func(ctx *Context) error {
return ctx.Write("Hello")
})
app.Run()}
這邊我們包裝的 Handle 使用了是 Return error 模式,相比標(biāo)準(zhǔn)庫(kù)只 Write 不 Return ,避免了不 Write 之后忘記 Return 導(dǎo)致的錯(cuò)誤,這通常很難發(fā)現(xiàn)。
一個(gè)Http Server 還需要一個(gè) middleware 功能,這里的思路就是在 Engine 中存放一個(gè) handleFunc 的數(shù)組,支持在外部注冊(cè),當(dāng)一個(gè)請(qǐng)求打過來時(shí)創(chuàng)建一個(gè)新 Ctx,將 Engine 中全局的 HandleFunc 復(fù)制到 Ctx 中,再使用 c.Next() 實(shí)現(xiàn)套娃式調(diào)用。
package httpimport (
"net/http")type Engine struct {
addr string
route map[string]handFunc
middlewares []handFunc}type Context struct {
w http.ResponseWriter
r *http.Request
index int
handlers []handFunc}type handFunc func(ctx *Context) errorfunc NewServer(addr string) *Engine {
return &Engine{
addr: addr,
route: make(map[string]handFunc),
middlewares: make([]handFunc, 0),
}}func (e *Engine) Run() {
err := http.ListenAndServe(e.addr, e)
if err != nil {
panic(err)
}}func (e *Engine) Use(middleware handFunc) {
e.middlewares = append(e.middlewares, middleware)}func (e *Engine) Get(path string, handle handFunc) {
e.route[path] = handle}func (e *Engine) handle(writer http.ResponseWriter, request *http.Request, handle handFunc) {
handlers := make([]handFunc, 0, len(e.middlewares)+1)
handlers = append(handlers, e.middlewares...)
handlers = append(handlers, handle)
ctx := &Context{
w: writer,
r: request,
index: -1,
handlers: handlers,
}
ctx.Next()}func (e *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {
handleF := e.route[req.URL.Path]
e.handle(w, req, handleF)}func (c *Context) Next() error {
c.index++
if c.index < len(c.handlers) {
return c.handlers[c.index](c)
}
return nil}func (c *Context) Write(s string) error {
_, err := c.w.Write([]byte(s))
return err}
實(shí)現(xiàn)方法很簡(jiǎn)單,這里我們驗(yàn)證一下是否可以支持前置和后置中間件
func TestHttp(t *testing.T) {
app := NewServer(":8080")
app.Get("/hello", func(ctx *Context) error {
fmt.Println("Hello")
return ctx.Write("Hello")
})
app.Use(func(ctx *Context) error {
fmt.Println("A1")
return ctx.Next()
})
app.Use(func(ctx *Context) error {
err := ctx.Next()
fmt.Println("B1")
return err })
app.Run()}
輸出:
=== RUN TestHttp
A1
Hello
B1
以上就是關(guān)于“Go Http Server框架如何快速實(shí)現(xiàn)”這篇文章的內(nèi)容,相信大家都有了一定的了解,希望小編分享的內(nèi)容對(duì)大家有幫助,若想了解更多相關(guān)的知識(shí)內(nèi)容,請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
標(biāo)題名稱:GoHttpServer框架如何快速實(shí)現(xiàn)
文章位置:http://www.chinadenli.net/article18/jsgdgp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供靜態(tài)網(wǎng)站、手機(jī)網(wǎng)站建設(shè)、云服務(wù)器、標(biāo)簽優(yōu)化、營(yíng)銷型網(wǎng)站建設(shè)、微信小程序
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)