# GO语言的修饰器编程

package main

import “fmt”

func decorator(f func(s string)) func(s string) {

    return func(s string) {
fmt.Println("Started")
f(s)
fmt.Println("Done")
}


}

func Hello(s string) {
fmt.Println(s)
}

func main() {
decorator(Hello)(“Hello, World!”)
}

hello := decorator(Hello)
hello(“Hello”)

package main

import (
“fmt”
“reflect”
“runtime”
“time”
)

type SumFunc func(int64, int64) int64

func getFunctionName(i interface{}) string {
return runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name()
}

func timedSumFunc(f SumFunc) SumFunc {
return func(start, end int64) int64 {

defer func(t time.Time) {
fmt.Printf("--- Time Elapsed (%s): %v ---\n",
getFunctionName(f), time.Since(t))
}(time.Now())

return f(start, end)


}
}

func Sum1(start, end int64) int64 {
var sum int64
sum = 0
if start > end {
start, end = end, start
}
for i := start; i <= end; i++ {
sum += i
}
return sum
}

func Sum2(start, end int64) int64 {
if start > end {
start, end = end, start
}
return (end - start + 1) * (end + start) / 2
}

func main() {

sum1 := timedSumFunc(Sum1)
sum2 := timedSumFunc(Sum2)

fmt.Printf(“%d, %d\n”, sum1(-10000, 10000000), sum2(-10000, 10000000))
}

1）有两个 Sum 函数，Sum1() 函数就是简单的做个循环，Sum2() 函数动用了数据公式。（注意：start 和 end 有可能有负数的情况）

2）代码中使用了 Go 语言的反射机器来获取函数名。

3）修饰器函数是 timedSumFunc()

\$ go run time.sum.go
— Time Elapsed (main.Sum1): 3.557469ms —
— Time Elapsed (main.Sum2): 291ns —
49999954995000, 49999954995000
HTTP 相关的一个示例

package main

import (
“fmt”
“log”
“net/http”
“strings”
)

func WithServerHeader(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
log.Println(“—>WithServerHeader()”)
w.Header().Set(“Server”, “HelloServer v0.0.1”)
h(w, r)
}
}

func hello(w http.ResponseWriter, r *http.Request) {
log.Printf(“Recieved Request %s from %s\n”, r.URL.Path, r.RemoteAddr)
fmt.Fprintf(w, “Hello, World! “+r.URL.Path)
}

func main() {
http.HandleFunc(“/v1/hello”, WithServerHeader(hello))
err := http.ListenAndServe(“:8080”, nil)
if err != nil {
log.Fatal(“ListenAndServe: “, err)
}
}

package main

import (
“fmt”
“log”
“net/http”
“strings”
)

func WithServerHeader(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
log.Println(“—>WithServerHeader()”)
w.Header().Set(“Server”, “HelloServer v0.0.1”)
h(w, r)
}
}

func WithAuthCookie(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
log.Println(“—>WithAuthCookie()”)
cookie := &http.Cookie{Name: “Auth”, Value: “Pass”, Path: “/”}
http.SetCookie(w, cookie)
h(w, r)
}
}

func WithBasicAuth(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
log.Println(“—>WithBasicAuth()”)
cookie, err := r.Cookie(“Auth”)
if err != nil || cookie.Value != “Pass” {
w.WriteHeader(http.StatusForbidden)
return
}
h(w, r)
}
}

func WithDebugLog(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
log.Println(“—>WithDebugLog”)
r.ParseForm()
log.Println(r.Form)
log.Println(“path”, r.URL.Path)
log.Println(“scheme”, r.URL.Scheme)
log.Println(r.Form[“url_long”])
for k, v := range r.Form {
log.Println(“key:”, k)
log.Println(“val:”, strings.Join(v, “”))
}
h(w, r)
}
}
func hello(w http.ResponseWriter, r *http.Request) {
log.Printf(“Recieved Request %s from %s\n”, r.URL.Path, r.RemoteAddr)
fmt.Fprintf(w, “Hello, World! “+r.URL.Path)
}

func main() {
http.HandleFunc(“/v1/hello”, WithServerHeader(WithAuthCookie(hello)))
http.HandleFunc(“/v2/hello”, WithServerHeader(WithBasicAuth(hello)))
http.HandleFunc(“/v3/hello”, WithServerHeader(WithBasicAuth(WithDebugLog(hello))))
err := http.ListenAndServe(“:8080”, nil)
if err != nil {
log.Fatal(“ListenAndServe: “, err)
}
}

type HttpHandlerDecorator func(http.HandlerFunc) http.HandlerFunc

func Handler(h http.HandlerFunc, decors …HttpHandlerDecorator) http.HandlerFunc {
for i := range decors {
d := decors[len(decors)-1-i] // iterate in reverse
h = d(h)
}
return h
}

http.HandleFunc(“/v4/hello”, Handler(hello,
WithServerHeader, WithBasicAuth, WithDebugLog))

func Decorator(decoPtr, fn interface{}) (err error) {
var decoratedFunc, targetFunc reflect.Value

    decoratedFunc = reflect.ValueOf(decoPtr).Elem()
targetFunc = reflect.ValueOf(fn)

v := reflect.MakeFunc(targetFunc.Type(),
func(in []reflect.Value) (out []reflect.Value) {
fmt.Println("before")
out = targetFunc.Call(in)
fmt.Println("after")
return
})

decoratedFunc.Set(v)
return


}

func foo(a, b, c int) int {
fmt.Printf(“%d, %d, %d \n”, a, b, c)
return a + b + c
}

func bar(a, b string) string {
fmt.Printf(“%s, %s \n”, a, b)
return a + b
}

type MyFoo func(int, int, int) int
var myfoo MyFoo
Decorator(&myfoo, foo)
myfoo(1, 2, 3)

mybar := bar
Decorator(&mybar, bar)
mybar(“hello,”, “world!”)

Again， 如果你有更好的写法，请你一定要告诉我。

（全文完）

#### Go语言编程

2018年01月31日 10.69MB 下载

#### Go语言编程_许式伟_完整版_.pdf )

2017年10月12日 9.74MB 下载

#### go示例2：模拟音乐播放器

2017-03-23 14:25:31

#### Go语言编程.pdf

2017年11月23日 8.83MB 下载

#### Go语言图形界面开发：Go版GTK

2018-02-08 21:17:27

#### go服务器与mfc做客户端的简单群聊Demo

2017-01-09 10:49:41

#### [Struts 2] decorator(sitemesh)修饰器的配置和使用

2014-11-06 14:40:22

#### Go语言编程--附带例子的源代码--许式伟 著--

2017年12月25日 9.12MB 下载

#### 《Go语言编程》pdf包括源代码精校版

2016年04月08日 9.13MB 下载

#### Go语言编程pdf

2018年01月19日 8.78MB 下载