Golang中HttpRouter路由的使用详解

 更新时间:2023年05月26日 14:40:39   作者:技术颜良  
httprouter 是一个高性能、可扩展的HTTP路由,本文将通过一些简单的示例为大家讲讲httprouter 这个强大的 HTTP 路由是如何使用的,感兴趣的小伙伴可以了解一下

httprouter

httprouter 是一个高性能、可扩展的HTTP路由,上面我们列举的net/http默认路由的不足,都被httprouter 实现,我们先用一个例子,认识下 httprouter 这个强大的 HTTP 路由。

安装:

go get -u github.com/julienschmidt/httprouter

在这个例子中,首先通过httprouter.New()生成了一个*Router路由指针,然后使用GET方法注册一个适配/路径的Index函数,最后*Router作为参数传给ListenAndServe函数启动HTTP服务即可。

package main
 
import (
    "log"
    "net/http"
 
    "github.com/julienschmidt/httprouter"
)
 
func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
    w.Write([]byte("Index"))
}
 
func main() {
    router := httprouter.New()
    router.GET("/", Index)
    log.Fatal(http.ListenAndServe(":8080", router))
}

httprouter 为所有的HTTP Method 提供了快捷的使用方式,只需要调用对应的方法即可。

func (r *Router) GET(path string, handle Handle) {
    r.Handle("GET", path, handle)
}
func (r *Router) HEAD(path string, handle Handle) {
    r.Handle("HEAD", path, handle)
}
func (r *Router) OPTIONS(path string, handle Handle) {
    r.Handle("OPTIONS", path, handle)
}
func (r *Router) POST(path string, handle Handle) {
    r.Handle("POST", path, handle)
}
func (r *Router) PUT(path string, handle Handle) {
    r.Handle("PUT", path, handle)
}
func (r *Router) PATCH(path string, handle Handle) {
    r.Handle("PATCH", path, handle)
}
func (r *Router) DELETE(path string, handle Handle) {
    r.Handle("DELETE", path, handle)
}

现代的API,基本上都是Restful API,httprouter提供的命名参数的支持,可以很方便的帮助我们开发Restful API。比如我们设计的API/user/flysnow,这这样一个URL,可以查看flysnow这个用户的信息,如果要查看其他用户的,比如zhangsan,我们只需要访问API/user/zhangsan即可。

URL包括两种匹配模式:/user/:name精确匹配、/user/*name匹配所有的模式。

package main
 
import (
  "github.com/julienschmidt/httprouter"
  "net/http"
  "log"
  "fmt"
)
 
 
func main()  {
  router:=httprouter.New()
  router.GET("/MainData", func (w http.ResponseWriter,r *http.Request,_ httprouter.Params)  {
    w.Write([]byte("default get"))
  })
  router.POST("/MainData",func (w http.ResponseWriter,r *http.Request,_ httprouter.Params)  {
    w.Write([]byte("default post"))
  })
  //精确匹配
  router.GET("/user/name",func (w http.ResponseWriter,r *http.Request,p httprouter.Params)  {
    w.Write([]byte("user name:"+p.ByName("name")))
  })
  //匹配所有
  router.GET("/employee/*name",func (w http.ResponseWriter,r *http.Request,p httprouter.Params)  {
    w.Write([]byte("employee name:"+p.ByName("name")))
  })
  http.ListenAndServe(":8081", router)
}

Handler处理链处理不同二级域名

package main
 
import (
    "fmt"
    "log"
    "net/http"
 
    "github.com/julienschmidt/httprouter"
)
 
type HostMap map[string]http.Handler
 
func (hs HostMap) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    fmt.Println("222")
    //根据域名获取对应的Handler路由,然后调用处理(分发机制)
    if handler := hs[r.Host]; handler != nil {
        handler.ServeHTTP(w, r)
    } else {
        http.Error(w, "Forbidden", 403)
    }
}
 
func main() {
    userRouter := httprouter.New()
    userRouter.GET("/", func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
        w.Write([]byte("play"))
    })
 
    dataRouter := httprouter.New()
    dataRouter.GET("/", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
        w.Write([]byte("tool"))
    })
 
    //分别用于处理不同的二级域名
    hs := make(HostMap)
    hs["user.localhost:12345"] = userRouter
    hs["data.localhost:12345"] = dataRouter
 
    log.Fatal(http.ListenAndServe(":12345", hs))
}

httprouter提供了很方便的静态文件服务,可以把一个目录托管在服务器上,以供访问。

router.ServeFiles("/static/*filepath",http.Dir("./"))

使用ServeFiles需要注意的是,第一个参数路径,必须要以/*filepath,因为要获取我们要访问的路径信息。

func (r *Router) ServeFiles(path string, root http.FileSystem) {
    if len(path) < 10 || path[len(path)-10:] != "/*filepath" {
        panic("path must end with /*filepath in path '" + path + "'")
    }
    fileServer := http.FileServer(root)
    r.GET(path, func(w http.ResponseWriter, req *http.Request, ps Params) {
        req.URL.Path = ps.ByName("filepath")
        fileServer.ServeHTTP(w, req)
    })
}

例子:

package main
import (
    "log"
    "net/http"
    "github.com/julienschmidt/httprouter"
)
func main() {
    router := httprouter.New()
  //访问静态文件
    router.ServeFiles("/static/*filepath", http.Dir("./files"))
    log.Fatal(http.ListenAndServe(":8080", router))
}

httprouter 异常捕获,httprouter允许使用者,设置PanicHandler用于处理HTTP请求中发生的panic。

package main
import (
    "fmt"
    "log"
    "net/http"
    "github.com/julienschmidt/httprouter"
)
func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
    panic("error")
}
func main() {
    router := httprouter.New()
    router.GET("/", Index)
  //捕获异常
    router.PanicHandler = func(w http.ResponseWriter, r *http.Request, v interface{}) {
        w.WriteHeader(http.StatusInternalServerError)
        fmt.Fprintf(w, "error:%s", v)
    }
    log.Fatal(http.ListenAndServe(":8080", router))
}

httprouter还有不少有用的小功能,比如对404进行处理,我们通过设置Router.NotFound来实现,我们看看Router这个结构体的配置,可以发现更多有用的功能。

type Router struct {
    //是否通过重定向,给路径自定加斜杠
    RedirectTrailingSlash bool
    //是否通过重定向,自动修复路径,比如双斜杠等自动修复为单斜杠
    RedirectFixedPath bool
    //是否检测当前请求的方法被允许
    HandleMethodNotAllowed bool
    //是否自定答复OPTION请求
    HandleOPTIONS bool
    //404默认处理
    NotFound http.Handler
    //不被允许的方法默认处理
    MethodNotAllowed http.Handler
    //异常统一处理
    PanicHandler func(http.ResponseWriter, *http.Request, interface{})
}

到此这篇关于Golang中HttpRouter路由的使用详解的文章就介绍到这了,更多相关Golang HttpRouter路由内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 构建go镜像实现过程全面讲解

    构建go镜像实现过程全面讲解

    这篇文章主要为大家介绍了构建go镜像实现过程全面讲解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-12-12
  • 一文带你了解Go语言fmt标准库输出函数的使用

    一文带你了解Go语言fmt标准库输出函数的使用

    这篇文章主要为大家详细介绍了Go语言中 fmt 标准库输出函数的使用,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起了解一下
    2022-12-12
  • 使用Go构建一款静态分析工具Owl详解

    使用Go构建一款静态分析工具Owl详解

    Owl是一款开源项目依赖分析工具,可以快速在指定的项目目录下查找符合某些特征的源代码文件或者依赖文件,这篇文章主要介绍了使用Go构建一款静态分析工具,需要的朋友可以参考下
    2022-06-06
  • Go语言数据结构之二叉树必会知识点总结

    Go语言数据结构之二叉树必会知识点总结

    如果你是一个开发人员,或多或少对树型结构都有一定的认识。二叉树作为树的一种,是一种重要的数据结构,也是面试官经常考的东西。本文为大家总结了一些二叉树必会知识点,需要的可以参考一下
    2022-08-08
  • Gin与Mysql实现简单Restful风格API实战示例详解

    Gin与Mysql实现简单Restful风格API实战示例详解

    这篇文章主要为大家介绍了Gin与Mysql实现简单Restful风格API示例详解,有需要的朋友可以借鉴参考下希望能够有所帮助,祝大家多多进步
    2021-11-11
  • 读取Go项目中的配置文件的方法

    读取Go项目中的配置文件的方法

    本文主要介绍了读取Go项目中的配置文件的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-06-06
  • 详解Go并发编程时如何避免发生竞态条件和数据竞争

    详解Go并发编程时如何避免发生竞态条件和数据竞争

    大家都知道,Go是一种支持并发编程的编程语言,但并发编程也是比较复杂和容易出错的。比如本篇分享的问题:竞态条件和数据竞争的问题
    2023-04-04
  • Golang中常见加密算法的总结

    Golang中常见加密算法的总结

    这篇文章主要为大家详细介绍了Golang中常见的一些加密算法的实现,文中的示例代码讲解详细,具有一定的学习价值,感兴趣的小伙伴可以了解一下
    2023-03-03
  • 使用Gin框架返回JSON、XML和HTML数据

    使用Gin框架返回JSON、XML和HTML数据

    Gin是一个高性能的Go语言Web框架,它不仅提供了简洁的API,还支持快速的路由和中间件处理,在Web开发中,返回JSON、XML和HTML数据是非常常见的需求,本文将介绍如何使用Gin框架来返回这三种类型的数据,需要的朋友可以参考下
    2024-08-08
  • 解决golang http.FileServer 遇到的坑

    解决golang http.FileServer 遇到的坑

    这篇文章主要介绍了解决golang http.FileServer 遇到的坑,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-12-12

最新评论