mirror of
https://github.com/gopl-zh/gopl-zh.github.com.git
synced 2025-09-12 22:52:05 +00:00
good good study, day day up!
This commit is contained in:
54
vendor/gopl.io/ch7/http3a/main.go
generated
vendored
Normal file
54
vendor/gopl.io/ch7/http3a/main.go
generated
vendored
Normal file
@@ -0,0 +1,54 @@
|
||||
// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan.
|
||||
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
|
||||
|
||||
// See page 195.
|
||||
|
||||
// Http3a is an e-commerce server that registers the /list and /price
|
||||
// endpoints by calling (*http.ServeMux).HandleFunc.
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func main() {
|
||||
db := database{"shoes": 50, "socks": 5}
|
||||
mux := http.NewServeMux()
|
||||
//!+main
|
||||
mux.HandleFunc("/list", db.list)
|
||||
mux.HandleFunc("/price", db.price)
|
||||
//!-main
|
||||
log.Fatal(http.ListenAndServe("localhost:8000", mux))
|
||||
}
|
||||
|
||||
type database map[string]int
|
||||
|
||||
func (db database) list(w http.ResponseWriter, req *http.Request) {
|
||||
for item, price := range db {
|
||||
fmt.Fprintf(w, "%s: $%d\n", item, price)
|
||||
}
|
||||
}
|
||||
|
||||
func (db database) price(w http.ResponseWriter, req *http.Request) {
|
||||
item := req.URL.Query().Get("item")
|
||||
if price, ok := db[item]; ok {
|
||||
fmt.Fprintf(w, "$%d\n", price)
|
||||
} else {
|
||||
w.WriteHeader(http.StatusNotFound) // 404
|
||||
fmt.Fprintf(w, "no such item: %q\n", item)
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
//!+handlerfunc
|
||||
package http
|
||||
|
||||
type HandlerFunc func(w ResponseWriter, r *Request)
|
||||
|
||||
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
|
||||
f(w, r)
|
||||
}
|
||||
//!-handlerfunc
|
||||
*/
|
Reference in New Issue
Block a user