go http的三种实现---2

package main

import (
	"io"
	"log"
	"net/http"
	"os"
)

func main() {
	//声明一个新的handler
	mux := http.NewServeMux()
	//注册路由
	mux.Handle("/", &handler{})
	//注册路由
	mux.HandleFunc("/index", index)

	//获取当前文件路径,进行静态文件输出
	wd, err := os.Getwd()
	if err != nil {
		log.Fatal(err)
	}
	mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir(wd))))

	//监听端口,并输出mux
	err = http.ListenAndServe(":8080", mux)
	if err != nil {
		log.Fatal(err)
	}
}

type handler struct{}

//必须实现的一个方法
func (*handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	io.WriteString(w, "URL:"+r.URL.String())
}
func index(w http.ResponseWriter, r *http.Request) {
	io.WriteString(w, "你好!")
}
原文地址:https://www.cnblogs.com/zheng-chuang/p/6083487.html