go http的三种实现---3

package main

//效率最高的一个方法
import (
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"strings"
	"time"
)

var mux map[string]func(http.ResponseWriter, *http.Request)

func main() {
	//声明一个server
	server := http.Server{
		Addr:        ":8080",         //监听端口
		Handler:     &handler{},      //handler
		ReadTimeout: 5 * time.Second, //监听超时
	}
	//路由列表
	mux = make(map[string]func(http.ResponseWriter, *http.Request))
	mux["/hello"] = hello

	//开始监听
	err := server.ListenAndServe()
	if err != nil {
		log.Fatal(err)
	}
}

type handler struct{}

func (*handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	//实现静态文件输出
	if strings.Contains(r.URL.String(), "/static/") {
		fmt.Println("111")
		wd, err := os.Getwd()
		if err != nil {
			log.Fatal(err)
		}
		//此处使用.Serve.HTTP(w, r)的原因参考下面资料
		http.StripPrefix("/static/", http.FileServer(http.Dir(wd))).ServeHTTP(w, r)
		return
	}
	//	动态匹配路由
	if h, ok := mux[r.URL.String()]; ok {
		//匹配成功执行函数
		h(w, r)
		return
	}
	//	没有匹配成功则输出URL
	io.WriteString(w, "URL:"+r.URL.String())
}

//输出hello
func hello(w http.ResponseWriter, r *http.Request) {
	io.WriteString(w, "hello")
}

参考资料

原文地址:https://www.cnblogs.com/zheng-chuang/p/6083492.html