1、HTTP服务
路由规则
• URL 分为两种,末尾是 /:表示⼀个⼦树,后⾯可以跟其他⼦路径; 末尾不
是 /,表示⼀个叶⼦,固定的路径
• 以/ 结尾的 URL 可以匹配它的任何⼦路径,⽐如 /images 会匹配 /images/
cute-cat.jpg
• 它采⽤最⻓匹配原则,如果有多个匹配,⼀定采⽤匹配路径最⻓的那个进⾏处
理• 如果没有找到任何匹配项,会返回 404 错误
package main
import (
"fmt"
"net/http"
"time"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello World!")
})
http.HandleFunc("/time/", func(w http.ResponseWriter, r *http.Request) {
t := time.Now()
timeStr := fmt.Sprintf("{\"time\": \"%s\"}", t)
w.Write([]byte(timeStr))
})
http.ListenAndServe(":8080", nil)
}
2、构建RESTful服务
// 国内源安装失败,切换成国外源才行
// go get github.com/julienschmidt/httprouter
package main
import (
"fmt"
"github.com/julienschmidt/httprouter"
"log"
"net/http"
)
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.Fprintf(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))
}
3、⾯向资源的架构(Resource Oriented Architecture)
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/julienschmidt/httprouter"
)
type Employee struct {
ID string `json:"id"`
Name string `json:"name"`
Age int `json:"age"`
}
var employeeDB map[string]*Employee
func init() {
employeeDB = map[string]*Employee{}
employeeDB["Mike"] = &Employee{"e-1", "Mike", 35}
employeeDB["Rose"] = &Employee{"e-2", "Rose", 45}
}
func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
fmt.Fprint(w, "Welcome!\n")
}
func GetEmployeeByName(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
qName := ps.ByName("name")
var (
ok bool
info *Employee
infoJson []byte
err error
)
if info, ok = employeeDB[qName]; !ok {
w.Write([]byte("{\"error\":\"Not Found\"}"))
return
}
if infoJson, err = json.Marshal(info); err != nil {
w.Write([]byte(fmt.Sprintf("{\"error\":,\"%s\"}", err)))
return
}
w.Write(infoJson)
}
func main() {
router := httprouter.New()
router.GET("/", Index)
router.GET("/employee/:name", GetEmployeeByName)
log.Fatal(http.ListenAndServe(":8080", router))
}