golang http 路由的轻量实现

分类:技术文档 - Golang | 阅读(349) | 发布于:2019-02-28 17:30

package main

import (
	"net/http"
	"fmt"
)

type Application struct {
	Route map[string]map[string]http.HandlerFunc
}

func NewApplication(route map[string]map[string]http.HandlerFunc) *Application{
	return &Application{Route:route}
}

//路由表初始化/注册路由
func (app *Application) HandleFunc(method, path string, f http.HandlerFunc) {
	if app.Route == nil {
		app.Route = make(map[string]map[string]http.HandlerFunc)
	}
	if app.Route[method] == nil {
		app.Route[method] = make(map[string]http.HandlerFunc)
	}
	app.Route[method][path] = f
}

//实现路由核心处理ServeHTTP方法
func (app *Application) ServeHTTP(res http.ResponseWriter, req *http.Request) {
	//写log
	fmt.Println(req.Method, req.URL.Path)

	//路由执行
	if f, ok := app.Route[req.Method][req.URL.Path]; ok {
		f(res, req)
	} else {
		res.WriteHeader(404)
		fmt.Fprintf(res, "404 Page Not Found")
	}
}

//Get路由注册
func (app *Application) Get(path string, HandlerFunc http.HandlerFunc) {
	app.HandleFunc("GET", path, HandlerFunc)
}

//Post路由注册
func (app *Application) Post(path string, HandlerFunc http.HandlerFunc) {
	app.HandleFunc("POST", path, HandlerFunc)
}

//启动Http
func (app *Application) Run(addr string) error {
	return http.ListenAndServe(addr, app)
}

//Get操作
func IndexHandel(res http.ResponseWriter, req *http.Request) {
	fmt.Fprintf(res, "Index Page")
}

//Get操作
func HomePageHandel(res http.ResponseWriter, req *http.Request) {
	fmt.Fprintf(res, "Show Homepage")
}

//Post操作
func EditHomePageHandel(res http.ResponseWriter, req *http.Request) {
	fmt.Fprintf(res, "Edit Homepage")
}

func main() {
	app := NewApplication(nil)
	app.Get("/", IndexHandel)
	app.Get("/home", HomePageHandel)
	app.Post("/home", EditHomePageHandel)

	err := app.Run(":8080")
	if err != nil {
		fmt.Println(err.Error())
	}
}

标签: