FileServer
创建文件服务器的时候,路径后面的/
别忘记。
mux := http.NewServeMux()
files := http.FileServer(http.Dir("/home"))
mux.Handle("/static/", http.StripPrefix("/static/", files))
mux.Handle("/", files)
Handle针对的是接口(实现方法 (w http.ResponseWriter, r *http.Request))
HandleFunc针对的是函数,参数为((w http.ResponseWriter, r *http.Request))
如果是使用”github.com/gorilla/mux”,可以使用PathPrefix限制路径的前缀,如下:
"github.com/gorilla/mux"
func main() {
r := mux.NewRouter()
r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("/home/wdy"))))
src := &http.Server{
Handler: r,
Addr: ":8000",
}
src.ListenAndServe()
}
Cookie
设置cookie时,name中间不能有空格
package main
import (
"fmt"
"net/http"
)
func setCookie(w http.ResponseWriter, r *http.Request) {
c1 := http.Cookie{
Name: "first_cookie",
Value: "Go Web Programming",
HttpOnly: true,
}
c2 := http.Cookie{
Name: "second_cookie",
Value: "Manning Publications Co",
HttpOnly: true,
}
http.SetCookie(w, &c1)
http.SetCookie(w, &c2)
}
func getCookie(w http.ResponseWriter, r *http.Request) {
c1, err := r.Cookie("first_cookie")
if err != nil {
fmt.Fprintln(w, "Cannot get the first cookie")
}
cs := r.Cookies()
fmt.Fprintln(w, c1)
fmt.Fprintln(w, cs)
}
func main() {
server := http.Server{
Addr: "127.0.0.1:8080",
}
http.HandleFunc("/set_cookie", setCookie)
http.HandleFunc("/get_cookie", getCookie)
server.ListenAndServe()
}