`
淘气天空lc
  • 浏览: 47933 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

GoLang adapter

 
阅读更多

看了下gopush的代码,被它的简洁震惊到了。。

http server  writed by golang

 

package main

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

//golang adapter //interface  func(ResponseWriter, *Request)
func ErrorHanler(f func(ResponseWriter,*Request)) http.HandlerFunc {
	return func(w ResponseWriter,r *Request){
		err := f(w,r)
		if err!= nil {
		  http.Error(w,err.Error(),http.StatusInternalServerError)
		}
	}
}
func errorHandler(f func(http.ResponseWriter, *http.Request) error) func(http.ResponseWriter,*http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		err := f(w, r)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	}
}

func betterHandler(w http.ResponseWriter, r *http.Request) error {
	fmt.Println("better Hanlder")
	return nil
}
func main() {
	fmt.Println(http.Dir("webapp"))
	http.Handle("/css/",http.FileServer(http.Dir("webapp")))
	http.Handle("/js/",http.FileServer(http.Dir("webapp")))
	http.HandleFunc("/login/",handler.GetLoginHanlder())
	http.HandleFunc("/admin/",handler.GetAdminHanlder())
	http.HandleFunc("/ajax/",handler.GetAjaxHanlder())
	http.HandleFunc("/",errorHandler(betterHandler))  // use adapter
	http.ListenAndServe(":8090",nil)

}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics