package web import ( "fmt" "net/http" "os" "os/signal" "syscall" "time" ) type Web struct { Port, ReadTimeout, WriteTimeout, IdleTimeout int handler http.Handler function func(string) (bool, func(r *http.Request)) } type Option func(web *Web) type Callback func(request *http.Request) func WithPort(port int) Option { return func(web *Web) { web.Port = port } } func WithReadTimeout(readTimeout int) Option { return func(web *Web) { web.ReadTimeout = readTimeout } } func WithWriteTimeout(writeTimeout int) Option { return func(web *Web) { web.WriteTimeout = writeTimeout } } func WithIdleTimeout(idleTimeout int) Option { return func(web *Web) { web.IdleTimeout = idleTimeout } } func WithHandler(handler http.Handler) Option { return func(web *Web) { web.handler = handler } } func WithFunction(function func(string) (bool, func(r *http.Request))) Option { return func(web *Web) { web.function = function } } func (this *Web) ServeHTTP(w http.ResponseWriter, r *http.Request) { //remoteUrl, _ := url.Parse("http://192.168.0.147:9000") fmt.Println(r.Host) //fmt.Println(r.RequestURI) if this.function != nil { pass, callback := this.function(r.Host) if !pass { _, _ = w.Write([]byte("403: Host forbidden")) return } if callback != nil { // 执行回调 callback(r) } } //hostProxy[host] = proxy // 放入缓存 //w.Write([]byte("403: Host forbidden " + r.Host)) this.handler.ServeHTTP(w, r) } func (this *Web) stop() { c := make(chan os.Signal) signal.Notify(c, os.Interrupt, os.Kill, syscall.SIGHUP, syscall.SIGTERM) go func() { defer func() { if err := recover(); err != nil { err = fmt.Errorf("internal error: %v", err) } }() s := <-c defer close(c) signal.Stop(c) fmt.Printf("Http Server Stop:Closed - %d\n", s) os.Exit(0) }() } func (this *Web) Run() { serve := &http.Server{ Addr: fmt.Sprintf(":%d", this.Port), Handler: this, ReadTimeout: time.Duration(this.ReadTimeout) * time.Second, WriteTimeout: time.Duration(this.WriteTimeout) * time.Second, IdleTimeout: time.Duration(this.IdleTimeout) * time.Second, MaxHeaderBytes: 1 << 20, } this.stop() fmt.Println("Http Server Start") fmt.Printf("Http Server Address - %v\n", fmt.Sprintf("http://127.0.0.1:%d", this.Port)) _ = serve.ListenAndServe() } func NewWeb(options ...Option) *Web { out := &Web{Port: 80} for _, option := range options { option(out) } return out }