diff --git a/g/net/ghttp/http_server.go b/g/net/ghttp/http_server.go index 59a6ff858..90d7f6896 100644 --- a/g/net/ghttp/http_server.go +++ b/g/net/ghttp/http_server.go @@ -154,10 +154,20 @@ func (s *Server) Run() error { // 开启异步处理队列处理循环 s.startCloseQueueLoop() // 执行端口监听 - if err := s.server.ListenAndServe(); err != nil { - glog.Error(err) - return err + if len(s.config.HTTPSCertPath) > 0 && len(s.config.HTTPSKeyPath) > 0 { + // HTTPS + if err := s.server.ListenAndServeTLS(s.config.HTTPSCertPath, s.config.HTTPSKeyPath); err != nil { + glog.Error(err) + return err + } + } else { + // HTTP + if err := s.server.ListenAndServe(); err != nil { + glog.Error(err) + return err + } } + s.status = 1 return nil } diff --git a/g/net/ghttp/http_server_config.go b/g/net/ghttp/http_server_config.go index efcf1b705..0675d929e 100644 --- a/g/net/ghttp/http_server_config.go +++ b/g/net/ghttp/http_server_config.go @@ -9,9 +9,7 @@ package ghttp import ( "time" - "log" "net/http" - "crypto/tls" ) // HTTP Server 设置结构体 @@ -19,12 +17,12 @@ type ServerConfig struct { // HTTP Server基础字段 Addr string // 监听IP和端口,监听本地所有IP使用":端口" Handler http.Handler // 默认的处理函数 - TLSConfig *tls.Config // TLS配置 + HTTPSCertPath string // HTTPS证书文件路径 + HTTPSKeyPath string // HTTPS签名文件路径 ReadTimeout time.Duration WriteTimeout time.Duration IdleTimeout time.Duration MaxHeaderBytes int // 最大的header长度 - ErrorLog *log.Logger // 错误日志的处理接口 // gf 扩展信息字段 IndexFiles []string // 默认访问的文件列表 IndexFolder bool // 如果访问目录是否显示目录列表 diff --git a/g/net/ghttp/http_server_options.go b/g/net/ghttp/http_server_options.go index cb6f4102d..c69fb8029 100644 --- a/g/net/ghttp/http_server_options.go +++ b/g/net/ghttp/http_server_options.go @@ -13,7 +13,6 @@ import ( "strconv" "strings" "net/http" - "crypto/tls" "gitee.com/johng/gf/g/os/gfile" ) @@ -59,12 +58,13 @@ func (s *Server)SetPort(port int) error { return nil } -// 设置http server参数 - TLSConfig -func (s *Server)SetTLSConfig(tls *tls.Config) error { +// 开启HTTPS支持,但是必须提供Cert和Key文件 +func (s *Server)EnableHTTPS(certFile, keyFile string) error { if s.status == 1 { return errors.New("server config cannot be changed while running") } - s.config.TLSConfig = tls + s.config.HTTPSCertPath = certFile + s.config.HTTPSKeyPath = keyFile return nil } diff --git a/geg/net/ghttp/https.go b/geg/net/ghttp/https.go new file mode 100644 index 000000000..ba2492647 --- /dev/null +++ b/geg/net/ghttp/https.go @@ -0,0 +1,15 @@ +package main + +import ( + "gitee.com/johng/gf/g/net/ghttp" +) + +func main() { + s := ghttp.GetServer() + s.BindHandler("/", func(r *ghttp.Request){ + r.Response.Writeln("哈喽世界!") + }) + s.EnableHTTPS("/home/john/temp/server.crt", "/home/john/temp/server.key") + s.SetPort(8199) + s.Run() +} \ No newline at end of file