day9接口 http.Handler接口
							parent
							
								
									e71b83ef5d
								
							
						
					
					
						commit
						56bdab679a
					
				|  | @ -0,0 +1,64 @@ | |||
| package main | ||||
| 
 | ||||
| import ( | ||||
| 	"fmt" | ||||
| 	"net/http" | ||||
| ) | ||||
| 
 | ||||
| type dollars float32 | ||||
| 
 | ||||
| func (d dollars) String() string { | ||||
| 	return fmt.Sprintf("$%.2f", d) | ||||
| } | ||||
| 
 | ||||
| type database map[string]dollars | ||||
| 
 | ||||
| func (db database) ServeHTTP(w http.ResponseWriter, req *http.Request) { | ||||
| 	switch req.URL.Path { | ||||
| 	case "/list": | ||||
| 		for item, price := range db { | ||||
| 			fmt.Fprintf(w, "%s: %s\n", item, price) | ||||
| 		} | ||||
| 	case "/price": | ||||
| 		item := req.URL.Query().Get("item") | ||||
| 		price, ok := db[item] | ||||
| 		if !ok { | ||||
| 			w.WriteHeader(http.StatusNotFound) // 404
 | ||||
| 			fmt.Fprintf(w, "no such item: %q\n", item) | ||||
| 			return | ||||
| 		} | ||||
| 		fmt.Fprintf(w, "%s\n", price) | ||||
| 	default: | ||||
| 		w.WriteHeader(http.StatusNotFound) // 404
 | ||||
| 		fmt.Fprintf(w, "no such page: %s\n", req.URL) | ||||
| 	} | ||||
| } | ||||
| 
 | ||||
| func (db database) list(w http.ResponseWriter, req *http.Request) { | ||||
| 	for item, price := range db { | ||||
| 		fmt.Fprintf(w, "%s: %s\n", item, price) | ||||
| 	} | ||||
| } | ||||
| 
 | ||||
| func (db database) price(w http.ResponseWriter, req *http.Request) { | ||||
| 	item := req.URL.Query().Get("item") | ||||
| 	price, ok := db[item] | ||||
| 	if !ok { | ||||
| 		w.WriteHeader(http.StatusNotFound) // 404
 | ||||
| 		fmt.Fprintf(w, "no such item: %q\n", item) | ||||
| 		return | ||||
| 	} | ||||
| 	fmt.Fprintf(w, "%s\n", price) | ||||
| 
 | ||||
| } | ||||
| func main() { | ||||
| 	db := database{"shoes": 50, "socks": 5} | ||||
| 	//http.ListenAndServe("localhost:8000", db)
 | ||||
| 	//mux := http.NewServeMux()
 | ||||
| 	//mux.Handle("/list", http.HandlerFunc(db.list))
 | ||||
| 	//mux.Handle("/price", http.HandlerFunc(db.price))
 | ||||
| 	//http.ListenAndServe("localhost:8000", mux)
 | ||||
| 	http.HandleFunc("/list", db.list) | ||||
| 	http.HandleFunc("/price", db.price) | ||||
| 	http.ListenAndServe("localhost:8000", nil) | ||||
| } | ||||
		Loading…
	
		Reference in New Issue