码迷,mamicode.com
首页 > 其他好文 > 详细

golang实现路由中间件middleware

时间:2019-07-07 17:56:38      阅读:349      评论:0      收藏:0      [点我收藏+]

标签:tco   isp   out   登录   path   contact   val   pac   splay   

registerHandlers.go

package router

import (
    "../ctrl"
    "../funcs"
    "github.com/julienschmidt/httprouter"
    "net/http"
)

type middleWareHandler struct {
    r *httprouter.Router
}

func NewMiddleWareHandler(r *httprouter.Router) http.Handler {
    m := middleWareHandler{}
    m.r = r
    return m
}

func (m middleWareHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    //检验合法性(session)
    ok := funcs.ValidateUser(r)
    if ok == false {
        funcs.Resp(w, -1, "请先登录", nil)
        return
    }
    m.r.ServeHTTP(w, r)
}

func RegisterHandlers() *httprouter.Router {
    router := httprouter.New()

    router.ServeFiles("/asset/*filepath", http.Dir("asset")) //启动静态资源服务
    router.POST("/user/login", ctrl.Login) //登陆
    router.POST("/user/register", ctrl.Register) //注册
    router.POST("/contact/addfriend", ctrl.AddFriend) //添加好友
    router.POST("/contact/loadfriend", ctrl.LoadFriend) //加载好友

    return router
}

main.go

package main

import (
    "./funcs"
    "./router"
    "html/template"
    "log"
    "net/http"
    "runtime"
)

var (
    AllConf funcs.Confs
    err     error
    tpl     *template.Template
    //SessionManager *funcs.Manager
)

//func init() {
//  SessionManager = funcs.Manager{}
//}

//循环渲染所有模版、路由方法
func DisplayView() {
    tpl, err = template.ParseGlob("view/**/*")
    //错误则不必再继续
    if err != nil {
        log.Fatal(err.Error())
    }
    for _, v := range tpl.Templates() {
        tplName := v.Name()
        http.HandleFunc(tplName, func(writer http.ResponseWriter, request *http.Request) {
            tpl.ExecuteTemplate(writer, tplName, nil)
        })
    }
}

func main() {
    //初始化配置
    if AllConf, err = funcs.InitConf("config.json"); err != nil {
        log.Fatal(err)
    }

    //初始化核心数
    runtime.GOMAXPROCS(runtime.NumCPU())

    //初始化数据库

    //渲染模版
    //DisplayView()

    //注册路由
    r := router.RegisterHandlers()
    mh := router.NewMiddleWareHandler(r)
    err := http.ListenAndServe(":80", mh)
    if err != nil {
        log.Fatal(err)
    }
}

golang实现路由中间件middleware

标签:tco   isp   out   登录   path   contact   val   pac   splay   

原文地址:https://blog.51cto.com/5660061/2417876

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!