httpserver支持路由传输控制器
2024-09-02 09:35:34
main.go
package main import (
"net/http" "com.jtthink.net/myhttpserver/core"
) type MyHandler struct { }
func(*MyHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request){ writer.Write([]byte("hello,myhandler"))
} func main() { router:=core.DefaultRouter() router.Add("/",&NewsController{}) http.ListenAndServe(":8099",router) }
NewsController.go
package main import "com.jtthink.net/myhttpserver/core" type NewsController struct {
core.MyController
} func(this *NewsController) GET() {
this.Ctx.WriteString("this is newscontroller")
} func(this *NewsController) POST() {
this.Ctx.WriteString("this is newscontroller for POST")
}
MyRouter.go
package core import (
"net/http"
)
type MyHandlerFunc func(ctx *MyContext)
type MyRouter struct {
Mapping map[string]ControllerInterface } func DefaultRouter() *MyRouter {
return &MyRouter{make(map[string]ControllerInterface)}
}
//加入 path 和Controller的对应关系
func(this *MyRouter) Add(path string,c ControllerInterface) {
this.Mapping[path]=c
} func(this *MyRouter) ServeHTTP(writer http.ResponseWriter, request *http.Request){
//chrome 会默认请求图标地址
if f,OK:=this.Mapping[request.URL.Path];OK{
f.Init(&MyContext{request,writer}) //关键代码
if request.Method=="GET"{//没有做防错处理
f.GET()
}
if request.Method=="POST"{//没有做防错处理
f.POST()
}
} }
MyController.go
package core type MyController struct {
Ctx *MyContext
} func(this *MyController) Init (ctx *MyContext) {
this.Ctx=ctx
} type ControllerInterface interface {
Init(ctx *MyContext)
GET()
POST()
}
MyContext.go
package core import "net/http" type MyContext struct { //上下文对象
request *http.Request
http.ResponseWriter
}
func(this *MyContext) WriteString(str string){
this.Write([]byte(str))
}
最新文章
- 小机房的树 codevs 2370
- mapreduce (五) MapReduce实现倒排索引 修改版 combiner是把同一个机器上的多个map的结果先聚合一次
- CCNA实验(1) -- 基本配置
- ButterKnife 绑定 RadioGroup
- Python数据库访问之SQLite3、Mysql
- 【HTML】谈谈html的meta标签
- 连表查询都用Left Join吧
- 3.HttpSession
- speech
- hdu5173 How Many Maos Does the Guanxi Worth
- linux防火墙使用以及配置
- 创建Pods私有库
- 5月14日 绿城育华NOIP巨石杯试卷解析
- TxQueryRunner-JDBC小工具
- geoserver REST使用
- Linux下添加FTP账号和服务器、增加密码和用户,更改FTP目录
- bzoj4561: [JLoi2016]圆的异或并 圆的扫描线
- css未知大小的图片居中
- HDUOJ---1233还是畅通工程
- 如何去掉drwxr-xr-x@中的@符号Linux文件扩展信息
热门文章
- js (function(){}()),(function(){})(),$(function(){});之间的区别
- Activiti历史查看
- sprignboot 中thymeleaf和freemarker 都存在时,默认选择哪个
- PHP CURL 异步测试
- [转]Expression Blend实例中文教程(8) - 动画设计快速入门StoryBoard
- [转]在C#代码中应用Log4Net系列教程(附源代码)
- 第四章 Odoo 12 开发之模块继承
- Django项目:CRM(客户关系管理系统)--80--70PerfectCRM实现CRM业务流程(bpm)课程排行分页
- 同名的cookie会不会存在多个
- java求1000以内的水仙花数