feat:完善项目信息

This commit is contained in:
henry
2022-01-05 16:09:55 +08:00
parent 822ced6041
commit 53c1f3912b
14 changed files with 352 additions and 922 deletions

View File

@ -3,6 +3,7 @@ package web
import (
"fmt"
"net/http"
"net/url"
"os"
"os/signal"
"syscall"
@ -10,15 +11,73 @@ import (
)
type Web struct {
*WebConfig
httpServer *http.Server
}
type WebConfig struct {
Port, ReadTimeout, WriteTimeout, IdleTimeout int
handler http.Handler
function func(string) (bool, func(r *http.Request))
}
type WebServer func(config *WebConfig) *Web
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(remoteUrl)
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)
@ -38,10 +97,10 @@ func (this *Web) stop() {
}()
}
func (this *Web) Run(handler http.Handler) {
this.httpServer = &http.Server{
func (this *Web) Run() {
serve := &http.Server{
Addr: fmt.Sprintf(":%d", this.Port),
Handler: handler,
Handler: this,
ReadTimeout: time.Duration(this.ReadTimeout) * time.Second,
WriteTimeout: time.Duration(this.WriteTimeout) * time.Second,
IdleTimeout: time.Duration(this.IdleTimeout) * time.Second,
@ -52,11 +111,14 @@ func (this *Web) Run(handler http.Handler) {
fmt.Println("Http Server Start")
fmt.Printf("Http Server Address - %v\n", fmt.Sprintf("http://127.0.0.1:%d", this.Port))
_ = this.httpServer.ListenAndServe()
_ = serve.ListenAndServe()
}
func NewWeb() WebServer {
return func(config *WebConfig) *Web {
return &Web{WebConfig: config}
func NewWeb(options ...Option) *Web {
out := &Web{Port: 80}
for _, option := range options {
option(out)
}
return out
}