golang的http.HandleFunc使用正则匹配路由

由于只是写一个博客,自定义一个路由器没(wo)有(hai)必(bu)要(hui),实现一个简单的路由即可

package router

import (
    "net/http"
    "zhfblog/controller"
    "regexp"
    "fmt"
)

// 路由定义
type routeInfo struct {
    pattern string                                       // 正则表达式
    f       func(w http.ResponseWriter, r *http.Request) //Controller函数
}

// 路由添加
var routePath = []routeInfo{
    routeInfo{"^/a/$", controller.Index},
}

// 使用正则路由转发
func Route(w http.ResponseWriter, r *http.Request) {
    isFound := false
    for _, p := range routePath {
        // 这里循环匹配Path,先添加的先匹配
        reg, err := regexp.Compile(p.pattern)
        if err != nil {
            continue
        }
        if reg.MatchString(r.URL.Path) {
            isFound = true
            p.f(w, r)
        }
    }
    if !isFound {
        // 未匹配到路由
        fmt.Fprint(w, "404 Page Not Found!")
    }
}

func init() {
    // 使用"/"匹配所有路由到自定义的正则路由函数Route
    // 只需在main包导入该路由包即可
    // import _ "zhfblog/router"
    http.HandleFunc("/", Route)
}

转载于:https://my.oschina.net/watcher/blog/758864

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值