Go语言设计模式(五)

2021-02-01 13:15

阅读:438

标签:服务器   work   content   handler   cli   http   pre   ons   sts   

 

Generator Pattern 生成器模式

Generators yields a sequence of values one at a time. 生成器一次生成一个值序列。
package main

import "fmt"

func Count(start int, end int) chan int {
	ch := make(chan int)
	go func(ch chan int) {
		for i := start; i 

  

Parallelism Pattern 并行模式

Parallelism allows multiple "jobs" or tasks to be run concurrently and asynchronously. 并行性允许多个“作业”或任务并发和异步运行
An example showing implementation and usage can be found in parallelism.go.  一个显示实现和使用的例子可以在parallel .go中找到。
 
Fan-In Messaging Patterns
Fan-In is a messaging pattern used to create a funnel for work amongst workers (clients: source, server: destination).  We can model fan-in using the Go channels.  扇入是一种消息传递模式,用于在工作者(客户端:源,服务器:目标)之间创建工作漏斗。我们可以使用Go通道来模拟扇入。
package main

import (
	"fmt"
	"sync"
)

func Merge(cs ...

  

 
装饰器模式
package main

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

func isAuthorized(endpoint func(http.ResponseWriter, *http.Request)) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

		fmt.Println("Checking to see if Authorized header set...")

		if val, ok := r.Header["Authorized"]; ok {
			fmt.Println(val)
			if val[0] == "true" {
				fmt.Println("Header is set! We can serve content!")
				endpoint(w, r)
			}
		} else {
			fmt.Println("Not Authorized!!")
			fmt.Fprintf(w, "Not Authorized!!")
		}
	})
}

func homePage(w http.ResponseWriter, r *http.Request) {
	fmt.Println("Endpoint Hit: homePage")
	fmt.Fprintf(w, "Welcome to the HomePage!")
}

func handleRequests() {

	http.Handle("/", isAuthorized(homePage))
	log.Fatal(http.ListenAndServe(":8081", nil))
}

func main() {
	handleRequests()
}

  

 

 

 

 

 

 

 

 

Go语言设计模式(五)

标签:服务器   work   content   handler   cli   http   pre   ons   sts   

原文地址:https://www.cnblogs.com/double-W/p/12813815.html


评论


亲,登录后才可以留言!