golang – http

常用包 Liemer_Lius 308℃

参考:Golang中如何实现GET请求

1. 普通示例:

package main

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

type dolors float32

func (d dolors) String() string {
    return (fmt.Sprintf("$%.2f", d))
}

type database map[string]dolors

func (db database) ServeHTTP(w http.ResponseWriter, req *http.Request) {
    for item, price := range db {
        fmt.Fprintf(w, "%s: %s\n", item, price)
    }
}

func main() {
    db := database{"Book": 23, "Shoes": 222}
    log.Fatal(http.ListenAndServe("localhost:8080", db))
}

2. URI路由:

package main

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

type dolors float32

func (d dolors) String() string {
    return (fmt.Sprintf("$%.2f", d))
}

type database map[string]dolors

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 item: %q\n", req.URL)
    }
}

func main() {
    db := database{"Book": 23, "Shoes": 222}
    log.Fatal(http.ListenAndServe("localhost:8080", db))
}

访问:http://localhost:8080
no such item: "/"

访问:http://localhost:8080/price?item=Book
$23.00

访问:http://localhost:8080/list
Shoes: $222.00
Book: $23.00

3. ServeMux实现

// 没有DefaultServeMux的调用
func main() {
    db := database{"Book": 23, "Shoes": 222}
    mux := http.NewServeMux()
    // http.HandlerFunc转换普通函数为http.Handler
    mux.Handle("/list", http.HandlerFunc(db.list))
    mux.Handle("/price", http.HandlerFunc(db.price))
    log.Fatal(http.ListenAndServe("localhost:8080", mux))
}

// DefaultServeMux的调用
func main() {
    db := database{"Book": 23, "Shoes": 222}
    http.HandleFunc("/list", db.list)
    http.HandleFunc("/price", db.price)
    // DefaultServeMux是全局的ServeMux实例,作为服务器的主程序,传入nil即可
    log.Fatal(http.ListenAndServe("localhost:8080", nil))
}

type dolors float32

func (d dolors) String() string {
    return (fmt.Sprintf("$%.2f", d))
}

type database map[string]dolors

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)
        fmt.Fprintf(w, "No such item: %q\n", item)
        return
    }
    fmt.Fprintf(w, "%s\n", price)
}

访问:
http://localhost:8080/hello
404 page not found

http://localhost:8080/list
Book: $23.00
Shoes: $222.00

http://localhost:8080/price?item=Book
$23.00

http://localhost:8080/price?item=Lius
No such item: "Lius"

4. HandlerFunc

package http

type HandlerFunc func(ResponseWriter, *Request)
// The HandlerFunc type is an adapter to allow the use of ordinary functions as HTTP handlers. If f is a function with the appropriate signature, HandlerFunc(f) is a Handler that calls f.
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) { f(w, r) }

HandlerFunc演示了Go语言接口机制的一个不常用的特性。
它不仅是一个函数类型,还拥有自己的方法,也满足接口http.Handler。
它的ServeHTTP方法就调用函数本身,所以HandlerFunc就是一个让函数值满足接口的一个适配器,函数和接口的唯一方法拥有同样的签名。

 

转载请注明:liutianfeng.com » golang – http

喜欢 (1)

评论已关闭。