GoWeb编程多路复用

在web编程中,比如我们要一个Url对应一个处理函数,或者一个页面对应一个静态文件,这些都需要进行处理,这个时候就是我们多路复用派上用场了。

package main

import "net/http"
import "fmt"

func index(writer http.ResponseWriter, request* http.Request) {
	fmt.Fprintf(writer, "index" )
}


func main() {

	//创建一个Http多路复用器
	mux := http.NewServeMux()

	//定义一个Http文件服务器,本机的绝对路径(大家可以试试自己机器上)
	files := http.FileServer(http.Dir("/Users/xxx/Desktop/GoApplication/static"))
	
	//去掉URL路径前缀,返回指定文件
	mux.Handle("/static/", http.StripPrefix("/static", files))
	
	//接收到URL为 ‘/’ 交给 index 函数处理
	mux.HandleFunc("/", index)
	
	//指定端口,传递多路复用器
	server := &http.Server{
		Addr : ":8080",
		Handler : mux,
	}
	server.ListenAndServe()
	
}







相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-12-07
  • 2022-03-05
  • 2022-12-23
  • 2022-01-05
  • 2021-10-22
猜你喜欢
  • 2021-09-02
  • 2021-09-03
  • 2021-09-08
  • 2021-08-15
  • 2021-09-30
  • 2022-12-23
相关资源
相似解决方案