第一个简单例子
package main
import "io"
import "log"
import "net/http"
func sayHello(w http.ResponseWriter,r *http.Request){
io.WriteString(w,"Hello world,this is version one.")
}
func main(){
//set route
http.HandleFunc("/",sayHello)
err:=http.ListenAndServe(":8080",nil)//default while the second parameter is nil
if err!=nil{
log.Fatal(err)
}
}
方式二
package main
import "io"
import "log"
import "net/http"
func main(){
mux:=http.NewServeMux()
mux.Handle("/",&myHandler{})
err:=http.ListenAndServe(":8080",mux)//default while the second parameter is nil
if err!=nil{
log.Fatal(err)
}
}
type myHandler struct{}
func (this *myHandler) ServeHTTP(w http.ResponseWriter,r *http.Request){//must have
io.WriteString(w,"URL:"+r.URL.String())
}
关于两个页面的统合
package main
import "io"
import "log"
import "net/http"
func main(){
mux:=http.NewServeMux()
mux.Handle("/",&myHandler{})//root for the muHandler
mux.HandleFunc("/hello",sayHello)//the page that you can skip to
err:=http.ListenAndServe(":8080",mux)//default while the second parameter is nil
if err!=nil{
log.Fatal(err)
}
}
type myHandler struct{}
func (this *myHandler) ServeHTTP(w http.ResponseWriter,r *http.Request){//must have
io.WriteString(w,"URL:"+r.URL.String())
}
func sayHello(w http.ResponseWriter,r *http.Request){
io.WriteString(w,"Hello world,this is version 2")
}
底层调用Server(最高效)
package main
import "io"
import "log"
import "net/http"
import "time"
var mux map[string]func(http.ResponseWriter,*http.Request)
func main(){
server := http.Server{
Addr:":8080",
Handler: &myHandler{},
ReadTimeout: 5*time.Second,
}
mux = make(map[string]func(http.ResponseWriter,*http.Request))
mux["/hello"]=sayHello
mux["/bye"]=sayBye
err:=server.ListenAndServe()
if err!=nil{
log.Fatal(err)
}
}
type myHandler struct{}
func (this *myHandler) ServeHTTP(w http.ResponseWriter,r *http.Request){//must have
if h,ok:=mux[r.URL.String()];ok{
h(w,r)
return
}
io.WriteString(w,"URL:"+r.URL.String())
}
func sayHello(w http.ResponseWriter,r *http.Request){
io.WriteString(w,"Hello world,this is version 2")
}
func sayBye(w http.ResponseWriter,r *http.Request){
io.WriteString(w,"Bye Bye,this is version 2")
}
实现静态目录
package main
import "io"
import "log"
import "net/http"
import "os"
func main(){
mux:=http.NewServeMux()
mux.Handle("/",&myHandler{})//root for the muHandler
mux.HandleFunc("/hello",sayHello)//the page that you can skip to
wd,err:=os.Getwd()//get the path
if err!=nil{
log.Fatal(err)
}
mux.Handle("/static/",
http.StripPrefix("/static/",
http.FileServer(http.Dir(wd))))
err=http.ListenAndServe(":8080",mux)//default while the second parameter is nil
if err!=nil{
log.Fatal(err)
}
}
type myHandler struct{}
func (this *myHandler) ServeHTTP(w http.ResponseWriter,r *http.Request){//must have
io.WriteString(w,"URL:"+r.URL.String())
}
func sayHello(w http.ResponseWriter,r *http.Request){
io.WriteString(w,"Hello world,this is version 2")
}