示例#1
0
文件: main.go 项目: rene-dev/twister
func main() {
	flag.Parse()
	h := web.SetErrorHandler(coreErrorHandler,
		web.ProxyHeaderHandler("X-Real-Ip", "X-Scheme",
			web.NewRouter().
				Register("/debug/<:.*>", "*", web.NewRouter().
					Register("/debug/expvar", "GET", expvar.ServeWeb).
					Register("/debug/pprof/<:.*>", "*", pprof.ServeWeb)).
				Register("/<:.*>", "*", web.FormHandler(10000, true, web.NewRouter().
					Register("/", "GET", homeHandler).
					Register("/core/file", "GET", web.FileHandler("static/file.txt", nil)).
					Register("/static/<path:.*>", "GET", web.DirectoryHandler("static/", nil)).
					Register("/chat", "GET", chatFrameHandler).
					Register("/chat/ws", "GET", chatWsHandler).
					Register("/mp", "GET", mpGetHandler, "POST", mpPostHandler).
					Register("/debug/pprof/<command>", "*", web.HandlerFunc(pprof.ServeWeb)).
					Register("/core/", "GET", coreHandler).
					Register("/core/a/<a>/", "GET", coreHandler).
					Register("/core/b/<b>/c/<c>", "GET", coreHandler).
					Register("/core/c", "POST", coreHandler)))))

	listener, err := net.Listen("tcp", ":8080")
	if err != nil {
		log.Fatal("Listen", err)
		return
	}
	defer listener.Close()
	err = (&server.Server{Listener: listener, Handler: h, Logger: server.LoggerFunc(server.VerboseLogger)}).Serve()
	if err != nil {
		log.Fatal("Server", err)
	}
}
示例#2
0
文件: main.go 项目: jonahglover/stuff
func main() {
	flag.Parse()
	for i := 0; i < *count; i++ {
		go run()
	}
	h := web.HandlerFunc(expvar.ServeWeb)
	server.Run("127.0.0.1:8081", h)
}
示例#3
0
// DebugFilter does various things (like reloading templates on each request if
// in debug mode).
func DebugFilter(enabled bool, config *lwb.BlogConfig, handler web.Handler) web.Handler {
	if !enabled {
		return handler
	}

	return web.HandlerFunc(func(req *web.Request) {
		ReloadTemplates(config)
		handler.ServeWeb(req)
	})
}
示例#4
0
func main() {
	flag.Parse()
	r := web.NewRouter().
		Register("/", "*", web.FormHandler(-1, false, web.HandlerFunc(handler))).
		Register("/static/<path:.*>", "GET", web.DirectoryHandler("static/", nil)).
		Register("/example/file.txt", "GET", web.FileHandler("static/file.txt", nil)).
		Register("/urlparam/<a>/<b>", "GET", handler).
		Register("/panic/before", "GET", web.HandlerFunc(panicBeforeResponse)).
		Register("/panic/after", "GET", web.HandlerFunc(panicAfterResponse)).
		Register("/limit", "POST", web.FormHandler(16, false, web.HandlerFunc(handler))).
		Register("/xsrf", "*", web.FormHandler(-1, true, web.HandlerFunc(handler))).
		Register("/multipart", "POST", multipartHandler).
		Register("/debug/expvar", "GET", expvar.ServeWeb).
		Register("/debug/pprof/<:.*>", "*", pprof.ServeWeb).
		Register("/proxy", "GET", web.ProxyHeaderHandler("X-Real-Ip", "X-Scheme", web.HandlerFunc(handler)))

	h := web.SetErrorHandler(errorHandler, r)

	if *useAdapter {
		log.Print("Running with adapter.")
		if err := http.ListenAndServe(*addr, adapter.HTTPHandler{h}); err != nil {
			log.Fatal(err)
		}
	} else {
		listener, err := net.Listen("tcp", *addr)
		if err != nil {
			log.Fatal("Listen", err)
		}
		defer listener.Close()
		if err := (&server.Server{Listener: listener, Handler: h, Logger: server.LoggerFunc(server.VerboseLogger)}).Serve(); err != nil {
			log.Fatal(err)
		}
	}
}
示例#5
0
func TestServer(t *testing.T) {
	for _, st := range serverTests {
		l := &testListener{done: make(chan bool), errs: st.errs}
		l.in.WriteString(st.in)
		if l.errs == nil {
			l.errs = defaultErrs
		}
		err := (&Server{Listener: l, Handler: web.HandlerFunc(testHandler)}).Serve()
		if err != os.EOF {
			t.Errorf("Server() = %v", err)
		}
		<-l.done
		out := l.out.String()
		if out != st.out {
			t.Errorf("in=%q\ngot:  %q\nwant: %q", st.in, out, st.out)
		}
		if l.readAll != st.readAll {
			t.Errorf("in=%q readAll = %v, want %v", st.in, l.readAll, st.readAll)
		}
	}
}
示例#6
0
func main() {
	flag.Parse()

	var err os.Error
	if config.BlogUrl, err = url.Parse(fmt.Sprintf("%s://%s", *flagProtocol, *flagHost)); err != nil {
		panic("Invalid protocol and/or host")
	}

	// Cache.
	if *flagCache {
		config.Cache = lwb.NewCache()
	} else {
		config.Cache = lwb.NewDummyCache()
	}

	// Initialize the database.
	db, _ := store.NewJsonStore(config, nil)

	// Context for rendering.
	tags := db.GetTags()
	categories := db.GetCategories()
	sort.Strings(tags)
	sort.Strings(categories)

	context := &handlers.RenderContext{
		Db:          db,
		Config:      config,
		Generator:   *flagGenerator,
		RecentPosts: db.GetRecentPosts(config.NumRecentPosts),
		Tags:        tags,
		Categories:  categories,
		Archives:    db.GetArchives(),
		UseCache:    *flagCache,
		Title:       config.Title,
		Path:        config.BlogUrl.String(),
	}

	// Templates...
	handlers.ReloadTemplates(config)

	// Example of adding file extension types for static file serving.
	fileMimeTypes := map[string]string{
		".eot":  "application/vnd.ms-fontobject",
		".otf":  "application/octet-stream",
		".ttf":  "application/x-font-ttf",
		".woff": "application/x-font-woff",
	}

	// Expiry for static content.
	const maxAge = 60 * 60 * 24 * 365 * 10
	fileHeaders := web.Header{
		web.HeaderExpires:      {fmt.Sprintf("%d", maxAge)},
		web.HeaderCacheControl: {fmt.Sprintf("max-age=%d", maxAge)},
	}

	serveFileOptions := &web.ServeFileOptions{fileMimeTypes, fileHeaders}

	// Register all path handlers.
	rh := handlers.DebugFilter(*flagDebug, config, web.NewRouter().
		// Stats.
		Register("/expvar", "GET", web.HandlerFunc(expvar.ServeWeb)).

		// Example of redirecting old blog urls to shiny new ones.
		Register("/index.shtml", "GET", web.RedirectHandler("/", true)).
		Register("/index.html", "GET", web.RedirectHandler("/", true)).
		Register("/bionew.shtml", "GET", web.RedirectHandler("/page/bio", true)).
		Register("/blogarchives/<path:.*>.shtml", "GET", func(req *web.Request) { pathHandler(req, "%s://%s/%s") }).
		Register("/blogarchives/<path:[^0-9].*>", "GET", func(req *web.Request) { pathHandler(req, "%s://%s/category/%s") }).
		Register("/blogarchives/<path:[0-9].*>", "GET", func(req *web.Request) { pathHandler(req, "%s://%s/%s") }).

		// Example of redirecting to feedburner.
		//Register("/index.xml", "GET", web.RedirectHandler("http://feeds.feedburner.com/steve-lacey-main", false)).

		// Handlers.
		Register(config.MainIndexRegexp, "GET", handlers.MainIndexHandler(context)).
		Register(config.RssFeedRegexp, "GET", handlers.RssFeedHandler(context)).
		Register(config.MonthlyArchiveRegexp, "GET", handlers.DateArchiveHandler(context)).
		Register(config.YearlyArchiveRegexp, "GET", handlers.DateArchiveHandler(context)).
		Register(config.TagArchiveRegexp, "GET", handlers.TagArchiveHandler(context,
			func(key string) ([]*store.Post, bool) { return db.GetPostsByTag(key) })).
		Register(config.CategoryArchiveRegexp, "GET", handlers.TagArchiveHandler(context,
			func(key string) ([]*store.Post, bool) { return db.GetPostsByCategory(key) })).
		Register(config.PostRegexp, "GET", handlers.SinglePostHandler(context)).
		Register(config.PageRegexp, "GET", handlers.PageHandler(context)).
		Register(config.StaticRegexp, "GET", web.DirectoryHandler("static/", serveFileOptions)))

	// Create a logger.
	logFile, err := os.OpenFile(*flagLog, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
	if err != nil {
		panic(fmt.Sprintf("Failed to open \"%s\": %s", *flagLog, err.String()))
	}

	defer logFile.Close()
	logger := server.NewApacheCombinedLogger(logFile)

	// Go!
	addr := fmt.Sprintf(":%d", *flagPort)
	fmt.Printf("Running on %s\n", addr)

	listener, err := net.Listen("tcp", addr)
	if err != nil {
		log.Fatal("Listen", err)
		return
	}

	defer listener.Close()
	err = (&server.Server{Listener: listener, Handler: rh, Logger: logger}).Serve()
	if err != nil {
		log.Fatal("Server", err)
	}
}
示例#7
0
func TestWebSocket(t *testing.T) {
	for _, tt := range webSocketTests {
		var test bytes.Buffer
		tt.header.WriteHttpHeader(&test)

		status, _, out := web.RunHandler("http://example.com/", "GET", tt.header, []byte(tt.in), web.HandlerFunc(testHandler))

		fail := status >= 400
		if fail != tt.fail {
			t.Errorf("%q, fail=%v, want %v; status %d", test.String(), fail, tt.fail, status)
			continue
		}

		if tt.fail {
			continue
		}

		br := bufio.NewReader(bytes.NewBuffer(out))
		br.ReadSlice('\n') // TODO: check correctness of status line
		header := make(web.Header)
		err := header.ParseHttpHeader(br)
		if err != nil {
			t.Errorf("%q, out=%q, header parse error %v", test.String(), string(out), err)
			continue
		}
		out, err = ioutil.ReadAll(br)
		if len(out) < 16 {
			t.Errorf("%q, expect 16 byte response, got %d", test.String(), len(out))
			continue
		}
		// TODO: check correctness of response.
		in := tt.in[8:] // remove key3
		out = out[16:]  // remove response

		// We expect the input to equal the output because the handler echoes
		// the messages.
		if string(out) != in {
			t.Errorf("%q, got %q", in, string(out))
		}
	}
}