router

1. router in golang

1). sample code

 1 package main
 2
 3 import (
 4     "fmt"
 5     "net/http"
 6 )
 7
 8 func main() {
 9
10     http.HandleFunc("/handlefunc", func(w http.ResponseWriter, r *http.Request) {
11         fmt.Fprintf(w, "http.HandleFunc")
12     })
13
14     http.Handle("/handle", &myHandler{})
15
16     http.ListenAndServe(":8080", nil)
17 }
18
19 type myHandler struct{}
20
21 func (this *myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
22     fmt.Fprintf(w, "http.Handle")
23 }

2). implement

a) top layer:

// Objects implementing the Handler interface can be
// registered to serve a particular path or subtree
// in the HTTP server.
//
// ServeHTTP should write reply headers and data to the ResponseWriter
// and then return.  Returning signals that the request is finished
// and that the HTTP server can move on to the next request on
// the connection.
type Handler interface {
    ServeHTTP(ResponseWriter, *Request)
}
// The HandlerFunc type is an adapter to allow the use of
// ordinary functions as HTTP handlers.  If f is a function
// with the appropriate signature, HandlerFunc(f) is a
// Handler object that calls f.
type HandlerFunc func(ResponseWriter, *Request)

// ServeHTTP calls f(w, r).
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
    f(w, r)
// Handle registers the handler for the given pattern
// in the DefaultServeMux.
// The documentation for ServeMux explains how patterns are matched.
func Handle(pattern string, handler Handler) { DefaultServeMux.Handle(pattern, handler) }

// HandleFunc registers the handler function for the given pattern
// in the DefaultServeMux.
// The documentation for ServeMux explains how patterns are matched.
func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
    DefaultServeMux.HandleFunc(pattern, handler)
}

Now we know that both of http.HandleFunc and http.Handle invoke function of DefaultServeMux.

b) DefaultServeMux

// NewServeMux allocates and returns a new ServeMux.
func NewServeMux() *ServeMux { return &ServeMux{m: make(map[string]muxEntry)} }

// DefaultServeMux is the default ServeMux used by Serve.
var DefaultServeMux = NewServeMux()
// ServeMux is an HTTP request multiplexer.
// It matches the URL of each incoming request against a list of registered
// patterns and calls the handler for the pattern that
// most closely matches the URL.
//
type ServeMux struct {
    mu    sync.RWMutex
    m     map[string]muxEntry
    hosts bool // whether any patterns contain hostnames
}

type muxEntry struct {
    explicit bool
    h        Handler
    pattern  string
}
// HandleFunc registers the handler function for the given pattern.
func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
    mux.Handle(pattern, HandlerFunc(handler))
}
// Handle registers the handler for the given pattern.
// If a handler already exists for pattern, Handle panics.
func (mux *ServeMux) Handle(pattern string, handler Handler) {
    mux.mu.Lock()
    defer mux.mu.Unlock()

    if pattern == "" {
        panic("http: invalid pattern " + pattern)
    }
    if handler == nil {
        panic("http: nil handler")
    }
    if mux.m[pattern].explicit {
        panic("http: multiple registrations for " + pattern)
    }

    mux.m[pattern] = muxEntry{explicit: true, h: handler, pattern: pattern}

    if pattern[0] != ‘/‘ {
        mux.hosts = true
    }

    // Helpful behavior:
    // If pattern is /tree/, insert an implicit permanent redirect for /tree.
    // It can be overridden by an explicit registration.
    n := len(pattern)
    if n > 0 && pattern[n-1] == ‘/‘ && !mux.m[pattern[0:n-1]].explicit {
        // If pattern contains a host name, strip it and use remaining
        // path for redirect.
        path := pattern
        if pattern[0] != ‘/‘ {
            // In pattern, at least the last character is a ‘/‘, so
            // strings.Index can‘t be -1.
            path = pattern[strings.Index(pattern, "/"):]
        }
        mux.m[pattern[0:n-1]] = muxEntry{h: RedirectHandler(path, StatusMovedPermanently), pattern: pattern}
    }
}

2. rounter in beego

时间: 2024-11-25 16:23:55

router的相关文章

ReactJS React+Redux+Router+antDesign通用高效率开发模板,夜间模式为例

工作比较忙,一直没有时间总结下最近学习的一些东西,为了方便前端开发,我使用React+Redux+Router+antDesign总结了一个通用的模板,这个技术栈在前端开发者中是非常常见的. 总的来说,我这个工程十分便捷,对于初学者来说,可能包含到以下的一些知识点: 一.React-Router的使用 Router是为了方便管理组件的路径,它使用比较简单,一般定义如下就行,需要注意的是,react-router的版本有1.0-3.0,各个版本对应的API大致相似,但也有不同,我使用的是2.X的,

openstack neutron 添加router

在neutron网络中,如果需要打通不同租户之间的软件网络,那么需要打开 neutron l3 agent,并且配置router: 配置/etc/neutron/l3_agent.ini #vi /etc/neutron/l3_agent.ini [DEFAULT] router_id = dbad9f1c-7999-4b1e-b307-c3466bb0eed9 use_namespaces = True auth_url = http://172.12.0.189:5000/v2.0/ adm

react router 4.0以上的路由应用

thead>tr>th{padding:8px;line-height:1.4285714;border-top:1px solid #ddd}.table>thead>tr>td,.table>tbody>tr>th,.table>tbody>tr>td,.table>tfoot>tr>th,.table>tfoot>tr>td{padding:8px;line-height:1.4285714;ver

Vue 路由设置router

由于学习的是router1.0的设置方法,但是现在都是支持2.0的,都报错,那些方法没定义,所以只好又来研究一下router2.0. vue-router2.0对路由的设置有了很大的改变,在HTML中将之前的用a标签link path改成了直接用一个router-link标签,但是你在网页审查元素会发现它还是一个a标签,router-view没有改变,在js中也将原本的router.map 直接改成了一个数组然后在new VueRouter时直接将数组用进去,将之前的挂载由router.star

关于egg.js的初次学习——controller和router的基本使用

今天学习了egg最基本的controller和router的使用. 首先什么是controller和router呢?controller就是经典的MVC(module,view,controller)架构中的controller层,主要用来解决实际的业务逻辑. router主要是用来分发来自页面的请求,然后把这个请求交给某个controller去做.此处来一个小栗子 1 module.exports = app => { 2 app.get('/', 'render.ejs'); 3 }; 这里

vue router 导入方式

vue router 的路由导入方式可用以下两种: 一:直接导入 import Hello from '@/components/Hello' @是在webpack.base.conf.js 配置: resolve: { extensions: ['.js', '.vue', '.json'], alias: { 'vue$': 'vue/dist/vue.esm.js', '@': resolve('src') } } 二 :路由懒加载方式 当打包构建应用时,Javascript包会变得非常大

The Difference Between a Router, Switch and Hub

Some technicians have a tendency to use the terms router, switch and hub interchangeably,  but have you ever wondered what the difference is? Some technicians have a tendency to use the terms router, hub and switch interchangeably. One minute they're

Router通过DHCP上网配置方法

1.此方法适用于猫自带拨号功能.4G无线猫等设备,其它步骤和平常配置router步骤并没有什么区别,只是在配置WAN口的时候有变化.2.首先IP-DHCP Client点击加号添加,选择WAN口是第几个口,然后确定.稍等上几秒,DHCP client界面显示出IP地址则表示连接成功.打开router list 会看到外网路由会自动添加好,这表示配置成功. 3.其它步骤和配普通router没什么区别.配置好后VPN也通,远程也可以访问.

[Angular Router] Lazy loading Module with Auxiliary router

Found the way to handle Auxiliary router for lazy loading moudle and erge load module are different. In Erge loading, it is recommended to create a shell component, inside shell component you need to define the router-outlet for each Auxiliary routes

[Angular2 Router] Optional Route Query Parameters - The queryParams Directive and the Query Parameters Observable

In this tutorial we are going to learn how to use the Angular 2 router to pass optional query parameters from one route into another route. There are couple of ways of doing this from the source route perspective: we use the queryParams property in t