Example #1
2
func init() {
	http.HandleFunc("/", handler)
	http.HandleFunc("/savetheme", saveThemeHandler)
	http.HandleFunc("/randomcolorswarm", randomColorWarmHandler)
	http.HandleFunc("/randomcolorshappy", randomColorHappyHandler)
	http.HandleFunc("/randomcolorssoft", randomColorSoftHandler)
}
Example #2
1
func (this *App) setHandlers() {
	fs := http.FileServer(http.Dir("static"))
	http.Handle("/static/", http.StripPrefix("/static/", fs))
	http.HandleFunc("/events", this.eventsHandler)
	http.HandleFunc("/event_history", this.eventHistoryHandler)
	http.HandleFunc("/", this.dashboardHandler)
}
Example #3
1
func setRouters() {
	http.HandleFunc("/", home)
	http.HandleFunc("/admin", MustLogin(admin))
	http.HandleFunc("/admin/login", login)
	http.HandleFunc("/admin/logout", MustLogin(logout))
	http.HandleFunc("/admin/list-tags", MustLogin(listTags))
}
Example #4
1
func main() {
	fmt.Println("starting server on http://localhost:3000/")
	http.HandleFunc("/", IndexHandler)
	http.HandleFunc("/redirect", CreateRedirectHandler)
	http.ListenAndServe(":3000", nil)

}
Example #5
0
func main() {
	flag.Parse()

	storageDriver, err := NewStorageDriver(*argDbDriver)
	if err != nil {
		glog.Fatalf("Failed to connect to database: %s", err)
	}

	containerManager, err := manager.New(storageDriver)
	if err != nil {
		glog.Fatalf("Failed to create a Container Manager: %s", err)
	}

	// Register Docker.
	if err := docker.Register(containerManager); err != nil {
		glog.Errorf("Docker registration failed: %v.", err)
	}

	// Register the raw driver.
	if err := raw.Register(containerManager); err != nil {
		glog.Fatalf("raw registration failed: %v.", err)
	}

	// Handler for static content.
	http.HandleFunc(static.StaticResource, func(w http.ResponseWriter, r *http.Request) {
		err := static.HandleRequest(w, r.URL)
		if err != nil {
			fmt.Fprintf(w, "%s", err)
		}
	})

	// Register API handler.
	if err := api.RegisterHandlers(containerManager); err != nil {
		glog.Fatalf("failed to register API handlers: %s", err)
	}

	// Redirect / to containers page.
	http.Handle("/", http.RedirectHandler(pages.ContainersPage, http.StatusTemporaryRedirect))

	// Register the handler for the containers page.
	http.HandleFunc(pages.ContainersPage, func(w http.ResponseWriter, r *http.Request) {
		err := pages.ServerContainersPage(containerManager, w, r.URL)
		if err != nil {
			fmt.Fprintf(w, "%s", err)
		}
	})

	defer glog.Flush()

	go func() {
		glog.Fatal(containerManager.Start())
	}()

	glog.Infof("Starting cAdvisor version: %q", info.VERSION)
	glog.Infof("About to serve on port ", *argPort)

	addr := fmt.Sprintf(":%v", *argPort)

	glog.Fatal(http.ListenAndServe(addr, nil))
}
Example #6
0
func main() {
	flag.Parse()
	templateManager, err := temple.New(*devMode, myTemplates, "templates")
	if err != nil {
		log.Fatal(err)
	}

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		ctx := homePageContext{
			baseContext{"Home"},
			[]string{"foo", "bar", "baz"},
		}
		// homepage composes shared templates by directly referencing "header" and "footer" templates.
		err := templateManager.Execute(w, ctx, "homepage")
		if err != nil {
			http.Error(w, err.Error(), 500)
		}
	})

	http.HandleFunc("/mc", func(w http.ResponseWriter, r *http.Request) {
		ctx := masterChildContext{
			baseContext{"Master / Child"},
			"AAAAA",
			"BBBBB",
		}
		// master / child templates let the library compose things for you
		// so no explicit reference to other templates is needed.
		err := templateManager.ExecuteMaster(w, ctx, "master", "child")
		if err != nil {
			http.Error(w, err.Error(), 500)
		}
	})
	http.ListenAndServe(":5555", nil)

}
Example #7
0
func main() {
	dat = make(map[string](map[string]string))
	reportlog = make(map[string](map[string]string))
	buf, _ := ioutil.ReadFile("static/data/data.json")
	if len(buf) > 0 {
		if err := json.Unmarshal(buf, &dat); err != nil {
			panic(err)
		}
	}
	buf, _ = ioutil.ReadFile("static/data/reportlog.json")
	if len(buf) > 0 {
		if err := json.Unmarshal(buf, &reportlog); err != nil {
			panic(err)
		}
	}
	http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
	http.HandleFunc("/", index)
	http.HandleFunc("/build", build) //设置访问的路由
	http.HandleFunc("/setdat", setdat)
	http.HandleFunc("/report", report)
	http.HandleFunc("/upload", UploadServer)
	err := http.ListenAndServe(dat["servermap"]["server"], nil) //设置监听的端口
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
Example #8
0
File: web.go Project: 2722/lantern
func startHttp() {
	http.HandleFunc("/register", register)
	http.HandleFunc("/unregister", unregister)
	laddr := fmt.Sprintf(":%d", *port)

	tlsConfig := tlsdefaults.Server()
	_, _, err := keyman.StoredPKAndCert(PKFile, CertFile, "Lantern", "localhost")
	if err != nil {
		log.Fatalf("Unable to initialize private key and certificate: %v", err)
	}
	cert, err := tls.LoadX509KeyPair(CertFile, PKFile)
	if err != nil {
		log.Fatalf("Unable to load certificate and key from %s and %s: %s", CertFile, PKFile, err)
	}
	tlsConfig.Certificates = []tls.Certificate{cert}

	log.Debugf("About to listen at %v", laddr)
	l, err := tls.Listen("tcp", laddr, tlsConfig)
	if err != nil {
		log.Fatalf("Unable to listen for tls connections at %s: %s", laddr, err)
	}

	log.Debug("About to serve")
	err = http.Serve(l, nil)
	if err != nil {
		log.Fatalf("Unable to serve: %s", err)
	}
}
Example #9
0
func configSwRoutes() {

	http.HandleFunc("/page/sw/time", func(w http.ResponseWriter, req *http.Request) {
		RenderDataJson(w, time.Now().Format("2006-01-02 15:04:05"))
	})

	http.HandleFunc("/page/sw/iprange", func(w http.ResponseWriter, req *http.Request) {
		RenderDataJson(w, strings.Join(g.Config().Switch.IpRange, "\n"))
	})

	http.HandleFunc("/page/sw/live", func(w http.ResponseWriter, req *http.Request) {
		RenderDataJson(w, len(funcs.AliveIp))
	})

	http.HandleFunc("/page/sw/list", func(w http.ResponseWriter, r *http.Request) {

		var ret [][]interface{} = make([][]interface{}, 0)
		for _, swSystem := range funcs.SwSystemInfo() {
			ret = append(ret,
				[]interface{}{
					swSystem.Ip,
					swSystem.Hostname,
					swSystem.Model,
					swSystem.Uptime,
					fmt.Sprintf("%d%%", swSystem.Cpu),
					fmt.Sprintf("%d%%", swSystem.Mem),
					fmt.Sprintf("%sms", swSystem.Ping),
				})
		}
		RenderDataJson(w, ret)
	})
}
func main() {

	http.HandleFunc("/locations", posting)
	http.HandleFunc("/locations/", posting)
	connectdb()
	log.Fatal(http.ListenAndServe(":8082", nil))
}
Example #11
0
func Startserver(b *gib.Board, addr string) {
	board = b
	http.HandleFunc("/catalog", cataloghandler)
	http.HandleFunc("/post", posthandler)
	http.HandleFunc("/postform", postformhandler)
	http.ListenAndServe(addr, nil)
}
Example #12
0
File: main.go Project: gwenn/gorace
func main() {
	fileServer := http.FileServer(http.Dir(STATIC_PATH))
	http.Handle("/", fileServer)

	http.HandleFunc("/laps", makeHandler(lapsHandler))
	http.HandleFunc(TIME_LOGS_URL, makeHandler(timeLogsHandler))
	http.HandleFunc("/results", makeHandler(resultsHandler))
	// admin pages
	http.HandleFunc("/race/", makeHandler(raceHandler))
	http.HandleFunc(TEAMS_URL, makeHandler(teamsHandler))

	var interrupted = make(chan os.Signal)
	go func() {
		<-interrupted
		closePool()
		trace("Bye bye")
		os.Exit(0)
	}()
	signal.Notify(interrupted, os.Interrupt)

	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		fatal("error running race webserver: %v\n", err)
	}
}
Example #13
0
func main() {

	// set the auth parameters
	auth.Config.CookieSecret = []byte("7H9xiimk2QdTdYI7rDddfJeV")
	auth.Config.LoginSuccessRedirect = "/private"
	auth.Config.CookieSecure = false

	// create the login handler
	endpoint := "https://accounts.google.com/o/openid2/auth"
	http.Handle("/auth/login", auth.OpenId(endpoint))

	// public urls
	http.HandleFunc("/", Public)

	// private, secured urls
	http.HandleFunc("/private", auth.SecureFunc(Private))

	// logout handler
	http.HandleFunc("/auth/logout", Logout)

	println("openid demo starting on port 8080")
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		fmt.Println(err)
	}
}
Example #14
0
func InitHandlers() {
	http.HandleFunc(UrlUploadSend, loghttp.Adapter(sendUpload))
	http.HandleFunc(UrlUploadReceive, loghttp.Adapter(receiveUpload))
	http.HandleFunc("/mnt00/", loghttp.Adapter(ServeDsFsFile))
	http.HandleFunc("/mnt01/", loghttp.Adapter(ServeDsFsFile))
	http.HandleFunc("/mnt02/", loghttp.Adapter(ServeDsFsFile))
}
Example #15
0
func main() {
	flag.Parse()

	yamlFile, err := ioutil.ReadFile(*configFile)

	if err != nil {
		log.Fatalf("Error reading config file: %s", err)
	}

	config := Config{}

	err = yaml.Unmarshal(yamlFile, &config)
	if err != nil {
		log.Fatalf("Error parsing config file: %s", err)
	}

	http.Handle("/metrics", prometheus.Handler())
	http.HandleFunc("/probe",
		func(w http.ResponseWriter, r *http.Request) {
			probeHandler(w, r, &config)
		})
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(`<html>
            <head><title>Blackbox Exporter</title></head>
            <body>
            <h1>Blackbox Exporter</h1>
            <p><a href="/probe?target=prometheus.io&module=http_2xx">Probe prometheus.io for http_2xx</a></p>
            <p><a href="/metrics">Metrics</a></p>
            </body>
            </html>`))
	})
	if err := http.ListenAndServe(*addr, nil); err != nil {
		log.Fatalf("Error starting HTTP server: %s", err)
	}
}
Example #16
0
func init() {
	http.HandleFunc("/", homeHandler)
	http.HandleFunc("/p/", proxyHandler)
	http.HandleFunc("/get/", getHandler)
	http.HandleFunc("/hello", helloHandler)
	http.Handle("/assets/", Assest.HTTPHandler("/"))
}
Example #17
0
func main() {

	// You should pass in your client key and secret key as args.
	// Or you can set your access key and secret key by replacing the default values below (2nd input param in flag.String)
	githubClientKey := flag.String("client_key", "[your github client key]", "your oauth client key")
	githubSecretKey := flag.String("secret_key", "[your github secret key]", "your oauth secret key")
	flag.Parse()

	// set the auth parameters
	auth.Config.CookieSecret = []byte("7H9xiimk2QdTdYI7rDddfJeV")
	auth.Config.LoginSuccessRedirect = "/private2"
	auth.Config.CookieSecure = false

	// login handler
	githubHandler := auth.Github(*githubClientKey, *githubSecretKey, "")
	http.Handle("/auth/login", githubHandler)

	// logout handler
	http.HandleFunc("/auth/logout", Logout)

	// public urls
	http.HandleFunc("/", Public)

	// private, secured urls
	http.HandleFunc("/private1", auth.SecureFunc(Private1))
	http.HandleFunc("/private2", auth.SecureUser(Private2))

	println("github demo starting on port 8080")
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		fmt.Println(err)
	}
}
Example #18
0
func main() {
	flag.Parse()

	sigHandler()

	http.Handle("/putask", &PutTaskHandler{})
	http.Handle("/getask", &GetTaskHandler{})
	http.Handle("/uptask", &UpTaskHandler{})
	http.Handle("/sayhi", &SayhiHandler{})
	http.HandleFunc("/newtype", HandleNewTaskType)
	http.HandleFunc("/beat", HandleBeat)

	http.Handle("/monitor", &MonitorHandler{})
	http.Handle("/web/", http.StripPrefix("/web/", http.FileServer(http.Dir("./static/"))))

	s := &http.Server{
		Addr:           ConfJson["listenaddr"].(string),
		ReadTimeout:    10 * time.Minute,
		WriteTimeout:   10 * time.Minute,
		MaxHeaderBytes: 1 << 20,
	}

	go RapperCleaner()

	fmt.Println("easytask GO...", ConfJson["listenaddr"].(string))
	if err := s.ListenAndServe(); err != nil {
		panic("ListenAndServe: " + err.Error())
	}
}
Example #19
0
func StartServer(args []string) {
	var err error
	const port_usage = "Port on which to serve HTTP API"

	flags := flag.NewFlagSet("start", flag.ExitOnError)
	flags.IntVar(&port, "port", 8080, port_usage)
	flags.IntVar(&port, "p", 8080, port_usage+" (shorthand)")
	flags.StringVar(&rpcSock, "sock", sock_default, sock_usage)
	flags.StringVar(&rpcSock, "s", sock_default, sock_usage+" (shorthand)")
	flags.Parse(args)

	adb, err = GetAndInitDB()
	if err != nil {
		panic(err)
	}

	rpcTornDown := make(chan int)
	go StartRPC(rpcSock, rpcTornDown, adb)

	http.HandleFunc("/", rootHandler)
	http.HandleFunc("/events", eventHandler)
	http.HandleFunc("/events/", eventHandler)

	//TODO add HTTPS, something like http://golang.org/pkg/net/http/#ListenAndServeTLS
	l, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
	if err != nil {
		panic(err)
	}
	defer l.Close()
	go http.Serve(l, nil)
	//TODO handle errors from http.Serve?

	asink.WaitOnExit()
	<-rpcTornDown
}
Example #20
0
func main() {
	if err := goa.Init(goa.Config{
		LoginPage:     "/login.html",
		HashKey:       []byte(hashKey),
		EncryptionKey: []byte(cryptoKey),
		CookieName:    "session",
		PQConfig:      "user=test_user password=test_pass dbname=goa",
	}); err != nil {
		log.Println(err)
		return
	}

	// public (no-auth-required) files
	http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(http.Dir("public"))))
	// protected files, only for logged-in users
	http.Handle("/protected/", goa.NewHandler(http.StripPrefix("/protected/", http.FileServer(http.Dir("protected")))))
	// home handler
	http.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) {
		http.ServeFile(rw, req, "index.html")
	})
	http.HandleFunc("/login.html", func(rw http.ResponseWriter, req *http.Request) {
		http.ServeFile(rw, req, "login.html")
	})
	http.HandleFunc("/register.html", func(rw http.ResponseWriter, req *http.Request) {
		http.ServeFile(rw, req, "register.html")
	})

	if err := http.ListenAndServeTLS(":8080", "keys/cert.pem", "keys/key.pem", nil); err != nil {
		log.Println(err)
	}
}
Example #21
0
// registerHandlers  services liveness probes.
func registerHandlers(s *staticPageHandler) {
	http.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
		// Delegate a check to the haproxy stats service.
		response, err := http.Get(fmt.Sprintf("http://localhost:%v", *statsPort))
		if err != nil {
			glog.Infof("Error %v", err)
			w.WriteHeader(http.StatusInternalServerError)
		} else {
			defer response.Body.Close()
			if response.StatusCode != http.StatusOK {
				contents, err := ioutil.ReadAll(response.Body)
				if err != nil {
					glog.Infof("Error reading resonse on receiving status %v: %v",
						response.StatusCode, err)
				}
				glog.Infof("%v\n", string(contents))
				w.WriteHeader(response.StatusCode)
			} else {
				w.WriteHeader(200)
				w.Write([]byte("ok"))
			}
		}
	})

	// handler for not matched traffic
	http.HandleFunc("/", s.Getfunc)

	glog.Fatal(http.ListenAndServe(fmt.Sprintf(":%v", lbApiPort), nil))
}
Example #22
0
func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("hello!"))
	})

	mw := multiWeatherProvider{
		openWeatherMap{apiKey: "632b34ca0a4a4b6a47104f86a25715af"},
		weatherUnderground{apiKey: "9cb0ff664cabfbda"},
	}

	http.HandleFunc("/weather/", func(w http.ResponseWriter, r *http.Request) {
		begin := time.Now()
		city := strings.SplitN(r.URL.Path, "/", 3)[2]

		temp, err := mw.temperature(city)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		w.Header().Set("Content-Type", "application/json; charset=utf-8")
		json.NewEncoder(w).Encode(map[string]interface{}{
			"city": city,
			"temp": temp,
			"took": time.Since(begin).String(),
		})
	})

	http.ListenAndServe(":8080", nil)
}
Example #23
0
func main() {
	cf := flag.String("config", "freegeoip.conf", "set config file")
	flag.Parse()
	if buf, err := ioutil.ReadFile(*cf); err != nil {
		log.Fatal(err)
	} else {
		conf = &Settings{}
		if err := xml.Unmarshal(buf, conf); err != nil {
			log.Fatal(err)
		}
	}
	templates = template.Must(template.ParseGlob(fmt.Sprintf("%s/template/*.html", conf.DocumentRoot)))
	http.Handle("/", http.FileServer(http.Dir(conf.DocumentRoot)))
	h := GeoipHandler()
	http.HandleFunc("/csv/", h)
	http.HandleFunc("/xml/", h)
	http.HandleFunc("/json/", h)
	http.HandleFunc("/map/", h)
	server := http.Server{
		Addr: conf.Addr,
		Handler: httpxtra.Handler{
			Logger:   logger,
			XHeaders: conf.XHeaders,
		},
		ReadTimeout:  15 * time.Second,
		WriteTimeout: 15 * time.Second,
	}
	log.Printf("FreeGeoIP server starting on %s (xheaders=%t)",
		conf.Addr, conf.XHeaders)
	if e := httpxtra.ListenAndServe(server); e != nil {
		log.Println(e.Error())
	}
}
Example #24
0
//封号
func SealHandler() {
	http.HandleFunc("/fbserver/seal/getAllSealAccount", GetAllSealAccount)
	http.HandleFunc("/fbserver/seal/addSealAccount", AddSealAccount)
	http.HandleFunc("/fbserver/seal/updateSealAccount", UpdateSealAccount)
	http.HandleFunc("/fbserver/seal/delSealAccount", DelSealAccount)
	http.HandleFunc("/fbserver/seal/getTotalByServerZoneIdAndGameId", TcpProtoIDFbSealGetTotalByServerZoneIdAndGameId)
}
Example #25
0
func configCommonRoutes() {
	http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("ok"))
	})

	http.HandleFunc("/version", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(g.VERSION))
	})

	http.HandleFunc("/workdir", func(w http.ResponseWriter, r *http.Request) {
		RenderDataJson(w, file.SelfDir())
	})

	http.HandleFunc("/config", func(w http.ResponseWriter, r *http.Request) {
		RenderDataJson(w, g.Config())
	})

	http.HandleFunc("/config/reload", func(w http.ResponseWriter, r *http.Request) {
		if strings.HasPrefix(r.RemoteAddr, "127.0.0.1") {
			g.ParseConfig(g.ConfigFile)
			RenderDataJson(w, "ok")
		} else {
			RenderDataJson(w, "no privilege")
		}
	})
}
Example #26
0
func main() {
	args, err := docopt.Parse(usage, nil, true, version, false)
	if err != nil {
		log.Fatal(err)
	}

	addr := args["--addr"].(string)
	if addr == ":8080" {
		envPort := os.Getenv("PORT")
		if envPort != "" {
			log.Println("using $PORT", envPort)
			addr = ":" + envPort
		}
	}

	http.HandleFunc("/", home)
	http.HandleFunc("/login", login)
	http.HandleFunc("/import", importStories)
	http.HandleFunc("/auth", auth)
	http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))

	log.Println("starting hn2instapaper server on", addr)
	if err := http.ListenAndServe(addr, nil); err != nil {
		log.Fatal(err)
	}
}
Example #27
0
func configAdminRoutes() {
	http.HandleFunc("/exit", func(w http.ResponseWriter, r *http.Request) {
		if g.IsTrustable(r.RemoteAddr) {
			w.Write([]byte("exiting..."))
			go func() {
				time.Sleep(time.Second)
				os.Exit(0)
			}()
		} else {
			w.Write([]byte("no privilege"))
		}
	})

	http.HandleFunc("/config/reload", func(w http.ResponseWriter, r *http.Request) {
		if g.IsTrustable(r.RemoteAddr) {
			g.ParseConfig(g.ConfigFile)
			RenderDataJson(w, g.Config())
		} else {
			w.Write([]byte("no privilege"))
		}
	})

	http.HandleFunc("/workdir", func(w http.ResponseWriter, r *http.Request) {
		RenderDataJson(w, file.SelfDir())
	})

	http.HandleFunc("/ips", func(w http.ResponseWriter, r *http.Request) {
		RenderDataJson(w, g.TrustableIps())
	})
}
Example #28
0
func init() {
	http.HandleFunc("/admin/", admin)
	http.HandleFunc("/admin/accept/", accept)
	http.HandleFunc("/admin/reject/", reject)
	http.HandleFunc("/admin/acceptremoval/", acceptremoval)
	http.HandleFunc("/admin/rejectremoval/", rejectremoval)
}
Example #29
0
func main() {
	http.HandleFunc("/view/", makeHandler(viewHandler))
	http.HandleFunc("/edit/", makeHandler(editHandler))
	http.HandleFunc("/save/", makeHandler(saveHandler))

	http.ListenAndServe(":8080", nil)
}
Example #30
0
func main() {
	googleMapsApiCredentials := "GOOGLE API Key - Browser"
	googleQPXExpressCredentials := "GOOGLE API Key - Server"
	geonameAccount := "GEONAME ACCOUNT"

	// install handlers
	go http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		data.DisplayDataEntry(w, r, googleMapsApiCredentials)
	})
	go http.HandleFunc("/selectAirports", func(w http.ResponseWriter, r *http.Request) {
		data.DisplayDataSelection(w, r, googleMapsApiCredentials, geonameAccount)
	})
	go http.HandleFunc("/dataVerification", func(w http.ResponseWriter, r *http.Request) {
		data.DisplayDataVerification(w, r, googleMapsApiCredentials)
	})
	go http.HandleFunc("/calculate", func(w http.ResponseWriter, r *http.Request) {
		calculate.DisplayCalculatePage(w, r, googleQPXExpressCredentials)
	})
	go http.HandleFunc("/refreshResults", func(w http.ResponseWriter, r *http.Request) {
		calculate.DisplayRefreshPagePage(w, r)
	})

	utils.OpenURL("http://localhost:80")

	// start web server
	http.ListenAndServe(":80", nil)
}