温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

golang实现路由中间件middleware

发布时间:2020-08-03 07:08:48 来源:网络 阅读:632 作者:梁十八 栏目:编程语言

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)
    }
}

还可以更灵活:
main.go

package main

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

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())

    //初始化数据库

    http.Handle("/user/login", http.HandlerFunc(ctrl.Login)) //登陆 post
    http.Handle("/user/register", http.HandlerFunc(ctrl.Register)) //注册 post
    http.Handle("/contact/addfriend", funcs.AuthLogin(http.HandlerFunc(ctrl.AddFriend))) //添加好友 get
    http.Handle("/contact/loadfriend", funcs.AuthLogin(http.HandlerFunc(ctrl.LoadFriend))) //加载好友 get

    err := http.ListenAndServe(":80", nil)
    if err != nil {
        log.Fatal(err)
    }
}

middleWare.go

package funcs

import (
    "../defs"
    "../model/redis"
    "encoding/json"
    "net/http"
)

//验证是否登陆
func AuthLogin(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        //验证...

    })
}

ctrl/addFriend.go

package ctrl

import (
    "../funcs"
    "../model"
    "fmt"
    "net/http"
    "strconv"
)

var contactModel model.Contact

func AddFriend(writer http.ResponseWriter, request *http.Request) {

    fmt.Println("addFriend")
    return

}
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI