时隔1年,又拣起了go。而且是我一直很想玩的go web。网上的资料大部分都不全,这里我会实现一个简单的商业项目,目前已经应用到公司的统计服务中。
废话不说,开go。
建立项目
首先,创建结构:
src--|
handlers--|
test--|
test.go
|
main.go
网上关于建立项目大部分都是使用默认的http.ListenAndServe。然而这是有局限的一种用法。因为默认的http封装,没有办法设置服务器的超时。正确的姿势应该是:
mux := http.NewServeMux()
server :=
http.Server{
Addr: fmt.Sprintf(":%d", 8080),
Handler: mux,
ReadTimeout: 3 * time.Second,
WriteTimeout: 5 * time.Second,
}
// 开始添加路由
mux.HandleFunc("/hi", test.SayHello)
server.ListenAndServe()
建议不要直接使用http.HandleFunc,因为操作的是默认的mux。这样不利于自定义。毕竟我们还是需要做点自己喜欢的事的。
test.go中,写一个很简单的handler。
package test
import "net/http"
func SayHello(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello"))
}
然后运行这个程序,就能在浏览器的localhost:8080/hi 中看到想看到的东西了。