httprouter 框架主要解决路由问题,github地址https://github.com/julienschmidt/httprouter

代码示例:

使用httprouter的服务

package main

import (
	"fmt"
	"log"
	"net/http"

	"github.com/julienschmidt/httprouter"
)

func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params)  {
	fmt.Fprint(w, "Welcome\n")
}

func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params)  {
	fmt.Fprint(w, "Hello, %s\n ", ps.ByName("name"))
}

func main()  {
	router := httprouter.New()
	router.GET("/", Index)
	router.GET("/hello/:name", Hello)
	log.Fatal(http.ListenAndServe(":8080", router))
}

原生的服务:

package main

import (
	"log"
	"net/http"
)

func main()  {
	http.HandleFunc("/", Hello2)
	err := http.ListenAndServe(":8081", nil)
	if err != nil {
		log.Fatal(err)
	}
}

func Hello2(writer http.ResponseWriter, request *http.Request) {
	writer.WriteHeader(200)
	writer.Write([]byte("sds"))
}