golang beego框架学习(九)

AndyYang| 阅读:1021 发表时间:2017-04-29 21:42:15 golang
摘要:本章节主要讲解go如何实现http中间键。

本章节主要讲解go如何实现http中间键。共有四个demo,附上demo1,更多请移步底部github。

Demo1,源码:
package main

import (
	"net/http"
)

type SingleHost struct {
	handler     http.Handler
	allowedHost string
}

/*func NewSingleHost(handler http.Handler, allowedHost string) *SingleHost {
	return &SingleHost{handler: handler, allowedHost: allowedHost}
}*/

func (s *SingleHost) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	host := r.Host
	if host == s.allowedHost {
		s.handler.ServeHTTP(w, r)
	} else {
		w.WriteHeader(403)
	}
}

func myHandler(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("Demo 1 is Success!"))
}

func main() {
	//single := NewSingleHost(http.HandlerFunc(myHandler), "localhost:8081")

	single := &SingleHost{
		handler:     http.HandlerFunc(myHandler),
		allowedHost: "webyang.net",
	}

	println("Listening on port 8081")
	http.ListenAndServe(":8081", single)
}

github:https://github.com/yangsir/beego_study

本文为AndyYang原创,转载请注明出处!
如果您觉得好,可以打赏作者:
如果您觉得累了,是否想看点美女养养眼:猛戳>>朋友帮
如果您觉得皮了,是否想来点神吐槽:猛戳>>iPhone查询中

已有0条评论

昵称:
邮箱:

  • 最新评论

iPhone查询中 - bbs.ipcxz.com 朋友帮 - www.pengyb.cn iPhone查询中 - bbs.ipcxz.com
反馈
微信订阅号