gf框架提供了非常强大的Web Server模块,由ghttp包支持,API文档地址: godoc.org/github.com/johng-cn/gf/g/net/ghttp。
哈喽世界!老规矩,我们先来一个Hello World:
package main
import "gitee.com/johng/gf/g/net/ghttp"
func main() {
s := ghttp.GetServer()
s.BindHandler("/", func(r *ghttp.Request){
r.Response.Write("哈喽世界!")
})
s.Run()
}
http://127.0.0.1/
ghttp.GetServer()单例模式
通过Run()方法执行Web Server的监听运行,在没有任何额外设置的情况下,它默认监听80端口。
关于其中的服务注册,我们将会在后续章节中介绍,我们继续来看看如何创建一个支持静态文件的Web Server。
Web Server创建并运行一个支持静态文件的Web Server:
package main
import "gitee.com/johng/gf/g/net/ghttp"
func main() {
s := ghttp.GetServer()
s.SetIndexFolder(true)
s.SetServerRoot("/home/www/")
s.Run()
}
Set*
SetIndexFolderSetServerRoot
Web Server默认情况下是没有任何主目录的设置,只有设置了主目录,才支持对应主目录下的静态文件的访问。更多属性设置请参考 ghttp API文档。
多服务器支持ghttp支持多Web Server运行,下面我们来看一个例子:
package main
import (
"gitee.com/johng/gf/g/net/ghttp"
)
func main() {
s1 := ghttp.GetServer("s1")
s1.SetPort(8080)
s1.SetIndexFolder(true)
s1.SetServerRoot("/home/www/static1")
go s1.Run()
s2 := ghttp.GetServer("s2")
s2.SetPort(8081)
s2.SetIndexFolder(true)
s2.SetServerRoot("/home/www/static2")
go s2.Run()
select{}
}
如果需要再同一个进程中支持多个Web Server,那么需要将每个Web Server使用goroutine进行异步执行监听,并且通过 select{} 语句(当然您也可以采用其他方式)保持主进程存活。
此外,可以看到我们在支持多个Web Server的语句中,给ghttp.GetServer传递了不同的参数,该参数为Web Server的名称,之前我们提到ghttp的GetServer方法采用了单例设计模式,该参数用于标识不同的Web Server,因此需要保证唯一性。
如果需要获取同一个Web Server,那么传入同一个名称即可。例如在多个goroutine中,或者不同的模块中,都可以通过ghttp.GetServer获取到同一个Web Server对象。
域名&多域名支持同一个Web Server支持多域名绑定,并且不同的域名可以绑定不同的服务。
我们来看一个简单的例子:
package main
import "gitee.com/johng/gf/g/net/ghttp"
func Hello1(r *ghttp.Request) {
r.Response.Write("127.0.0.1: Hello1!")
}
func Hello2(r *ghttp.Request) {
r.Response.Write("localhost: Hello2!")
}
func main() {
s := ghttp.GetServer()
s.Domain("127.0.0.1").BindHandler("/", Hello1)
s.Domain("localhost").BindHandler("/", Hello2)
s.Run()
}
http://127.0.0.1/http://localhost/
Domain
s.Domain("localhost1,localhost2,localhost3").BindHandler("/", Hello2)
这条语句的表示将Hello2方法注册到指定的3个域名中(localhost1~3),对其他域名不可见。
需要注意的是:Domain方法的参数必须是准确的域名,不支持泛域名形式,例如:*.johng.cn或者.johng.cn是不支持的,api.johng.cn或者johng.cn才被认为是正确的域名参数。