func main() { var addr = flag.String("addr", ":8080", "アプリケーションのアドレス") flag.Parse() gomniauth.SetSecurityKey(signature.RandomKey(64)) gomniauth.WithProviders( google.New( os.Getenv("client_id"), os.Getenv("client_secret"), "http://localhost:8080/auth/callback/google")) r := newRoom(UseFileSystemAvatar) http.Handle("/chat", MustAuth(&templateHandler{filename: "chat.html"})) http.Handle("/login", &templateHandler{filename: "login.html"}) http.HandleFunc("/logout", func(w http.ResponseWriter, r *http.Request) { http.SetCookie(w, &http.Cookie{ Name: "auth", Value: "", Path: "/", MaxAge: -1, }) w.Header().Set("Location", "/chat") w.WriteHeader(http.StatusTemporaryRedirect) }) http.HandleFunc("/auth/", loginHandler) http.Handle("/room", r) http.Handle("/upload", &templateHandler{filename: "upload.html"}) http.HandleFunc("/uploader", uploaderHandler) http.Handle("/avatars/", http.StripPrefix("/avatars/", http.FileServer(http.Dir("./avatars")))) go r.run() log.Println("Webサーバーを開始します。ポート: ", *addr) if err := http.ListenAndServe(*addr, nil); err != nil { log.Fatal("ListenAndServe:", err) } }
func main() { var addr = flag.String("addr", ":8080", "app address") flag.Parse() gomniauth.SetSecurityKey(signature.RandomKey(64)) gomniauth.WithProviders( google.New("391625238451-97uhiqpmehlvmgc48f5dscu2qi933v4l.apps.googleusercontent.com", "eqjo3wv_tXr6i9FJlgFiYRKD", "http://localhost:8080/auth/callback/google"), ) r := newRoom() r.tracer = trace.New(os.Stdout) // http.Handle("/", &templateHandler{filename: "chat.html"}) http.Handle("/chat", MustAuth(&templateHandler{filename: "chat.html"})) http.Handle("/login", &templateHandler{filename: "login.html"}) http.HandleFunc("/logout", func(w http.ResponseWriter, r *http.Request) { http.SetCookie(w, &http.Cookie{ Name: "auth", Value: "", Path: "/", MaxAge: -1, }) w.Header()["Location"] = []string{"/chat"} w.WriteHeader(http.StatusTemporaryRedirect) }) http.HandleFunc("/auth/", loginHandler) http.Handle("/room", r) go r.run() log.Println("launching server port :", *addr) if err := http.ListenAndServe(*addr, nil); err != nil { log.Fatal("ListenAndServe:", err) } }
func _main() { var addr = flag.String("addr", ":8080", "アプリケーションのアドレス") var callbackURL = flag.String("google-oauth-callback", "http://localhost:8080/auth/callback/google", "Google認証のコールバックURL") flag.Parse() gomniauth.SetSecurityKey(signature.RandomKey(64)) gomniauth.WithProviders( google.New(os.Getenv("GOOGLE_OAUTH_CLIENT_ID"), os.Getenv("GOOGLE_OAUTH_CLIENT_SECRET"), *callbackURL), ) r := newRoom() r.tracer = trace.New(os.Stdout) http.Handle("/chat", MustAuth(&templateHandler{filename: "index.html"})) http.Handle("/login", &templateHandler{filename: "login.html"}) http.HandleFunc("/auth/", loginHandler) http.Handle("/room", r) go r.run() log.Println("Webサーバーを開始します。ポート: ", *addr) log.Println("Google認証のコールバックURL: ", *callbackURL) if err := http.ListenAndServe(*addr, nil); err != nil { log.Fatal("ListenAndServe: ", err) } }
// Generates a 32 character random signature func main() { commander.Go(func() { commander.Map(commander.DefaultCommand, "", "", func(args objx.Map) { fmt.Println(signature.RandomKey(32)) }) commander.Map("len length=(int)", "Key length", "Specify the length of the generated key", func(args objx.Map) { length := args.Get("length").Int() fmt.Println(signature.RandomKey(length)) }) }) }
func init() { gomniauth.SetSecurityKey(signature.RandomKey(64)) gomniauth.WithProviders( google.New("712450255947-o5uppfp82sc3sb2c1dum7es8k93ras4q.apps.googleusercontent.com", "TrFX1I5QJZ_unJ-P5UgYLF4N", PalvelimenOsoite+"/authcallback/google"), ) gob.Register(User{}) }
func main() { var addr = flag.String("addr", ":8080", "The addr of the application") flag.Parse() // parse the flag gomniauth.SetSecurityKey(signature.RandomKey(64)) gomniauth.WithProviders( google.New("605169096484-hvgf6b5u60cdv0krm7r106b1v4lsuvk9.apps.googleusercontent.com", "0F1iTCjapfcoFUupsINMc-6X", "http://localhost:8080/auth/callback/google"), ) r := newRoom() r.tracer = trace.New(os.Stdout) http.HandleFunc("/logout", func(w http.ResponseWriter, r *http.Request) { http.SetCookie(w, &http.Cookie{ Name: "auth", Value: "", Path: "/", MaxAge: -1, }) w.Header()["Location"] = []string{"/chat"} w.WriteHeader(http.StatusTemporaryRedirect) }) http.Handle("/chat", MustAuth(&templateHandler{filename: "chat.html"})) http.Handle("/login", &templateHandler{filename: "login.html"}) http.Handle("/upload", &templateHandler{filename: "upload.html"}) http.Handle("/avatars/", http.StripPrefix("/avatars/", http.FileServer(http.Dir("./avatars")))) http.HandleFunc("/uploader", uploaderHandler) http.HandleFunc("/auth/", loginHandler) http.Handle("/room", r) // get the room going go r.run() // start the web server log.Println("Starting web server on", *addr) if err := http.ListenAndServe(*addr, nil); err != nil { log.Fatal("ListenAndServe:", err) } }
func (c *Configuration) StartAuth() { clientSecret := c.Json.ClientSecret if !c.Json.RunLocalMode { if os.Getenv("CRASHMAT_CLIENTSECRET") != "" { log.Println("Using environmental for CRASHMAT_CLIENTSECRET") clientSecret = os.Getenv("CRASHMAT_CLIENTSECRET") } } clientId := c.Json.ClientId if !c.Json.RunLocalMode { if os.Getenv("CRASHMAT_CLIENTID") != "" { log.Println("Using environmental for CRASHMAT_CLIENTID") clientId = os.Getenv("CRASHMAT_CLIENTID") } } gomniauth.SetSecurityKey(signature.RandomKey(64)) gomniauth.WithProviders(github.New(clientId, clientSecret, c.Json.GithubAuthCallback)) }
func main() { var addr = flag.String("addr", ":8080", "アプリケーションのアドレス") flag.Parse() // フラグを解釈します // Gomniauth のセットアップ gomniauth.SetSecurityKey(signature.RandomKey(64)) gomniauth.WithProviders( facebook.New(os.Getenv("FACEBOOK_APP_ID"), os.Getenv("FACEBOOK_APP_SECRET"), "http://localhost:8080/auth/callback/facebook"), github.New(os.Getenv("GITHUB_APP_ID"), os.Getenv("GITHUB_APP_SECRET"), "http://localhost:8080/auth/callback/github"), google.New(os.Getenv("GOOGLE_APP_ID"), os.Getenv("GOOGLE_APP_SECRET"), "http://localhost:8080/auth/callback/google"), ) r := newRoom() http.Handle("/chat", MustAuth(&templateHandler{filename: "chat.html"})) http.Handle("/login", &templateHandler{filename: "login.html"}) http.HandleFunc("/auth/", loginHandler) http.HandleFunc("/logout", func(w http.ResponseWriter, r *http.Request) { http.SetCookie(w, &http.Cookie{ Name: "auth", Value: "", Path: "/", MaxAge: -1, }) w.Header()["Location"] = []string{"/chat"} w.WriteHeader(http.StatusTemporaryRedirect) }) http.Handle("/room", r) http.Handle("/upload", &templateHandler{filename: "upload.html"}) http.HandleFunc("/uploader", uploaderHandler) http.Handle("/avatars/", http.StripPrefix("/avatars/", http.FileServer(http.Dir("./avatars")))) // チャットルームを開始します go r.run() // Web サーバを開始します log.Println("Webサーバを開始します。ポート: ", *addr) if err := http.ListenAndServe(*addr, nil); err != nil { log.Fatal("ListenAndServe:", err) } }
func main() { flag.StringVar(&appDir, "app-dir", "", "Path to grafana installation") flag.StringVar(&dbDir, "db-dir", "dashboards", "Path to dashboard storage dir") flag.StringVar(&authDomain, "auth-domain", "", "OAuth2 domain users must authenticated from (mydomain.com)") flag.StringVar(&basicAuth, "auth", "", "Basic auth username (user:pw)") flag.StringVar(&sessionSecret, "session-secret", defaultSessionSecret, "Session secret key") flag.StringVar(&httpAddr, "http-addr", ":8080", "HTTP Server bind address") flag.StringVar(&httpsAddr, "https-addr", ":8443", "HTTPS Server bind address") flag.StringVar(&graphiteURL, "graphite-url", "", "Graphite URL (http://host:port)") flag.StringVar(&influxDBURL, "influxdb-url", "", "InfluxDB URL (http://host:8086/db/mydb)") flag.StringVar(&influxDBUser, "influxdb-user", "", "InfluxDB username") flag.StringVar(&influxDBPass, "influxdb-pass", "", "InfluxDB password") flag.StringVar(&openTSDBUrl, "opentsdb-url", "", "OpenTSDB URL (http://host:4242)") flag.StringVar(&sslCert, "ssl-cert", "", "SSL cert (PEM formatted)") flag.StringVar(&sslKey, "ssl-key", "", "SSL key (PEM formatted)") flag.StringVar(&hostAddr, "host-addr", "http://localhost:8080", "Public server address (http://mydomain.com)") flag.StringVar(&googleClientID, "google-client-id", "", "Google Oauth2 Client ID") flag.StringVar(&googleClientSecret, "google-client-secret", "", "Google Oauth2 Client Sercret") flag.BoolVar(&version, "version", false, "show version") flag.Parse() if version { println(buildVersion) return } if sessionSecret == defaultSessionSecret { log.Printf("WARN: Session secret key is using the hard-coded default. Use -session-secret <value> for a live deployment.\n") } if graphiteURL == "" && influxDBURL == "" && openTSDBUrl == "" { fmt.Printf("No graphite-url, influxdb-url or opentsdb-url specified.\nUse -graphite-url http://host:port or -influxdb-url http://host:8086/db/mydb or -opentsdb-url http://host:4242\n") return } log.Printf("Starting gofana %s", buildVersion) if _, err := os.Stat(dbDir); os.IsNotExist(err) { fmt.Printf("%s does not exist. Creating.\n", dbDir) err := os.Mkdir(dbDir, 0766) if err != nil { fmt.Printf("ERROR: %s\n", err) return } } db = &DashboardRepository{Dir: dbDir} err := db.Load() if err != nil { fmt.Printf("ERROR: %s\n", err) return } logger := log.New(os.Stderr, "", log.LstdFlags) r := martini.NewRouter() m := martini.New() m.Map(logger) m.Use(martini.Recovery()) m.MapTo(r, (*martini.Routes)(nil)) m.Action(r.Handle) if sslCert != "" && sslKey != "" { m.Use(secure.Secure(secure.Options{})) } b := make([]byte, 32) _, err = rand.Read(b) if err != nil { fmt.Printf("ERROR: %s\n", err) return } m.Use(sessions.Sessions("session", sessions.NewCookieStore([]byte(sessionSecret)))) if oauthEnabled() { if authDomain == "" { fmt.Println("ERROR: No -auth-domain specified. Cannot authenticate with OAuth2.\n") return } gomniauth.SetSecurityKey(signature.RandomKey(64)) providers := gomniauth.WithProviders() if googleOauthEnabled() { providers.Add(google.New(googleClientID, googleClientSecret, fmt.Sprintf("%s/google/oauth2callback", hostAddr))) } m.Use(loginRequired) } m.Use(addCorsHeaders) m.Use(render.Renderer()) if basicAuth != "" && strings.Contains(basicAuth, ":") { parts := strings.Split(basicAuth, ":") m.Use(auth.Basic(parts[0], parts[1])) } var static martini.Handler if appDir == "" { static = staticbin.Static("grafana-1.9.1", grafana.Asset) } else { static = martini.Static(appDir, martini.StaticOptions{Fallback: "/index.html", Exclude: "/api/v"}) } r.NotFound(static, http.NotFound) r.Get("/search", searchDashboards) r.Get("/dashboard/:id", getDashboard) r.Post("/dashboard/:id", saveDashboard) r.Delete("/dashboard/:id", deleteDashboard) r.Get("/plugins/datasource.gofana.js", gofanaDatasource) r.Get("/config.js", gofanaConfig) r.Get("/graphite/**", proxyGraphite) r.Post("/graphite/**", proxyGraphite) r.Get("/influxdb/**", proxyInfluxDB) r.Post("/influxdb/**", proxyInfluxDB) r.Get("/opentsdb/**", proxyOpenTSDB) r.Post("/opentsdb/**", proxyOpenTSDB) r.Get("/:provider/auth", authRedirect) r.Get("/:provider/oauth2callback", oauth2callback) r.Get("/signin", getSignin) // HTTP Listener wg.Add(1) go func() { defer wg.Done() log.Printf("HTTP listening on %s\n", httpAddr) if err := http.ListenAndServe(httpAddr, m); err != nil { log.Fatal(err) } }() // HTTPS Listener if sslCert != "" && sslKey != "" { wg.Add(1) go func() { defer wg.Done() log.Printf("HTTPS listening on %s", httpsAddr) if err := http.ListenAndServeTLS(httpsAddr, sslCert, sslKey, m); err != nil { log.Fatal(err) } }() } wg.Wait() }
func newAuthenticator(cfg *config) authenticator { gomniauth.SetSecurityKey(signature.RandomKey(64)) a := &defaultAuthenticator{cfg} return a }
// Register adds a new email // to the DB func (db DB) Register(s string, email string, expiration time.Time) AuthToken { sig := Signature(signature.RandomKey(64)) db[sig] = AuthToken{sig, expiration, email} return db[sig] }
func main() { var configFileName string if len(os.Args) > 1 { configFileName = os.Args[1] } else { configFileName = os.Getenv(goimgshareConfigPathEnv) } if configFileName == "" { _, file := filepath.Split(os.Args[0]) log.Printf("Syntax error. Must specify the configuration file either as ") log.Printf("environmental variable (%s) or as first command argument.", goimgshareConfigPathEnv) log.Fatalf("%s program exiting.", file) return } log.Printf("Opening %s", configFileName) file, err := os.Open(configFileName) if err != nil { panic(fmt.Sprintf("Cannot open configuration file: %s ", err)) } defer file.Close() conf, err = config.Load(file) if err != nil { panic(fmt.Sprintf("Failed to load configuration file: %s ", err)) } gomniauth.SetSecurityKey(signature.RandomKey(64)) aDB = authdb.New() smallThumbCache = thumb.New(conf.ThumbnailCacheFolder, conf.SmallThumbnailSize, conf.SmallThumbnailSize) avgThumbCache = thumb.New(conf.ThumbnailCacheFolder, conf.AverageThumbnailSize, conf.AverageThumbnailSize) // load folders fmt.Printf("conf.SharedFoldersConfigurationFile == %s", conf.SharedFoldersConfigurationFile) file, err = os.Open(conf.SharedFoldersConfigurationFile) if err != nil { panic(fmt.Sprintf("Cannot open shared folder configuration file: %s ", err)) } defer file.Close() phyFolders, err = physical.Load(file) if err != nil { panic(err) } // end load folders var prov []common.Provider var providers []string if conf.Google != nil { providers = append(providers, "google") prov = append(prov, google.New(conf.Google.ClientID, conf.Google.Secret, conf.Google.ReturnURL)) } if conf.Facebook != nil { providers = append(providers, "facebook") prov = append(prov, facebook.New(conf.Facebook.ClientID, conf.Facebook.Secret, conf.Facebook.ReturnURL)) } if conf.Github != nil { providers = append(providers, "github") prov = append(prov, github.New(conf.Github.ClientID, conf.Github.Secret, conf.Github.ReturnURL)) } gomniauth.WithProviders(prov...) router := mux.NewRouter().StrictSlash(true) router.HandleFunc("/", logHandler(requireAuth(handleStatic(staticDirectoryAuth, "index.html")))) router.HandleFunc("/folders", logHandler(requireAuth(handleFolders))) // images rImages := regexp.MustCompile("(.*[.]jpg$)|(.*[.]gif$)|(.*[.]png$)") router.HandleFunc("/images/{folderid}", logHandler(requireAuth(handleFolder( func(strtomatch string) bool { return rImages.MatchString(strings.ToLower(strtomatch)) })))) //videos rVideos := regexp.MustCompile("(.*[.]mp4$)|(.*[.]mkv$)|(.*[.]avi$)") router.HandleFunc("/videos/{folderid}", logHandler(requireAuth(handleFolder( func(strtomatch string) bool { return rVideos.MatchString(strings.ToLower(strtomatch)) })))) // everyting else router.HandleFunc("/extra/{folderid}", logHandler(requireAuth(handleFolder( func(strtomatch string) bool { return !(rVideos.MatchString(strings.ToLower(strtomatch)) || rImages.MatchString(strings.ToLower(strtomatch))) })))) // serve the files router.HandleFunc("/file/{folderid}/{fn}", logHandler(requireAuth(handleStaticFile))) // handle thumbnails router.HandleFunc("/smallthumb/{folderid}/{fn}", logHandler(requireAuth(handleThumbnail))) router.HandleFunc("/avgthumb/{folderid}/{fn}", logHandler(requireAuth(handleThumbnail))) // register all the static content with NO authentication files, err := ioutil.ReadDir(filepath.Join(conf.InternalHTTPFilesPath, staticDirectory, staticDirectoryNoAuth)) if err != nil { panic(fmt.Sprintf("Cannot access static content folder: %s", err)) } for _, file := range files { path := path.Join("/", staticDirectory, file.Name()) log.Printf("Registering %s with noauth", path) if conf.LogInternalHTTPFilesAccess { router.HandleFunc(path, logHandler(handleStatic(staticDirectoryNoAuth, file.Name()))) } else { router.HandleFunc(path, handleStatic(staticDirectoryNoAuth, file.Name())) } } // register all the static content with authentication files, err = ioutil.ReadDir(filepath.Join(conf.InternalHTTPFilesPath, staticDirectory, staticDirectoryAuth)) if err != nil { panic(fmt.Sprintf("Cannot access static content folder: %s", err)) } for _, file := range files { path := path.Join("/", staticDirectory, file.Name()) log.Printf("Registering %s with auth", path) if conf.LogInternalHTTPFilesAccess { router.HandleFunc(path, logHandler(requireAuth(handleStatic(staticDirectoryAuth, file.Name())))) } else { router.HandleFunc(path, requireAuth(handleStatic(staticDirectoryAuth, file.Name()))) } } http.HandleFunc("/", logHandler(requireAuth(handleStatic(staticDirectoryAuth, "index.html")))) for _, provider := range providers { router.HandleFunc(fmt.Sprintf("/auth/%s/login", provider), loginHandler(provider)) router.HandleFunc(fmt.Sprintf("/auth/%s/callback", provider), callbackHandler(provider)) } router.HandleFunc("/supportedAuths", logHandler(handleSupportedAuths)) if conf.HTTPSCertificateFile != "" && conf.HTTPSCertificateKeyFile != "" { log.Printf("Starting encrypted TLS webserver on port %d...", conf.Port) if err := http.ListenAndServeTLS(fmt.Sprintf(":%d", conf.Port), conf.HTTPSCertificateFile, conf.HTTPSCertificateKeyFile, router); err != nil { log.Fatalf("ERROR starting webserver: %s", err) } } else { log.Printf("Starting non encrypted webserver on port %d...", conf.Port) if err := http.ListenAndServe(fmt.Sprintf(":%d", conf.Port), router); err != nil { log.Fatalf("ERROR starting webserver: %s", err) } } // http.ListenAndServeTLS() }
func main() { log.Info("Glasgow Memories Server") log.Info("=======================") utils.InitEnv() var Address = ":" + utils.EnvPort() var baseURL = utils.EnvUrl() m.Connect() defer m.Close() // prepare the decryption key if utils.LoadCypherKey() != nil { log.Error("Failed to load the decryption key.") return } // GOMNIAUTH gomniauth.SetSecurityKey(signature.RandomKey(64)) gomniauth.WithProviders( facebook.New("1497244403859030", "fbbb08c47e0441bcf23ea82b5f340fe5", baseURL+"/api/auth/facebook/callback/"), ) // Attach the DB collection references to the context in order to pass it around goweb.MapBefore(func(ctx context.Context) error { var user = m.User{} cookieC, err := ctx.HttpRequest().Cookie("token") var cookie string if err != nil { cookie = ctx.FormValue("token") if cookie == "" { return nil } } else { cookie = cookieC.Value } err = m.GetDB("User").Find(bson.M{"token": cookie}).One(&user) if err != nil { // log.Info("MapBefore 2 " + err.Error()) return nil } ctx.Data()["user"] = user return nil }) goweb.MapStatic("/static", "../static") // This is the directory with all static UI files goweb.MapStatic("/uploads", "../uploads") // This is the directory where we should store uploaded files // ENDPOINTS goweb.Map("GET", "/", endpoints.Root) goweb.Map("POST", "api/auth/local/register", endpoints.Register) goweb.Map("POST", "api/auth/local/login", endpoints.Login) goweb.Map("GET", "api/auth/{provider}/callback", endpoints.Callback) goweb.Map([]string{"GET", "POST"}, "api/auth/{provider}/{action}", endpoints.Connect) goweb.Map("POST", "api/upload/image", endpoints.UploadImage) goweb.Map("GET", "api/images/get", endpoints.GetImages) goweb.Map("POST", "api/upload/csv", endpoints.UploadTrail) goweb.Map("GET", "api/trails/get", endpoints.GetTrails) goweb.Map("POST", "api/upload/video", endpoints.UploadVideo) goweb.Map("GET", "api/videos/get", endpoints.GetVideos) goweb.Map("GET", "api/user", endpoints.GetUserInfo) goweb.Map("GET", "api/stats/get", endpoints.GetStats) goweb.Map("GET", "api/popLocations", endpoints.GetPopularLocations) goweb.Map("POST", "api/upload/imagetable", endpoints.UploadImageTable) goweb.Map("POST", "api/upload/zip", endpoints.UploadZip) // TODO: Add new endpoints here goweb.Map(endpoints.NotFound) // Remove the information from the data just in case the call is intercepted goweb.MapAfter(func(ctx context.Context) error { ctx.Data()["user"] = "" return nil }) // setup the API responder codecService := services.NewWebCodecService() codecService.RemoveCodec("text/xml") apiResponder := responders.NewGowebAPIResponder(codecService, goweb.Respond) apiResponder.StandardFieldDataKey = "data" apiResponder.StandardFieldStatusKey = "status" apiResponder.StandardFieldErrorsKey = "errors" goweb.API = apiResponder // SERVER s := &http.Server{ Addr: Address, Handler: goweb.DefaultHttpHandler(), ReadTimeout: 5 * time.Minute, WriteTimeout: 5 * time.Minute, MaxHeaderBytes: 1 << 20, } c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt) listener, listenErr := net.Listen("tcp", Address) log.Info("Server port: " + Address) log.Info("Server running at: " + baseURL + "\n") if listenErr != nil { log.Error("Could not listen: " + listenErr.Error()) } go func() { for _ = range c { // sig is a ^C, handle it // stop the HTTP server log.Info("Stopping the server...\n") listener.Close() log.Info("Server stopped.\n") } }() // begin the server log.Error("Error in Serve: " + s.Serve(listener).Error()) }
func main() { // reading configuration file and creating "configuration" object to store // values file, _ := os.Open("conf.json") decoder := json.NewDecoder(file) configuration := Configuration{} err := decoder.Decode(&configuration) if err != nil { fmt.Println("error:", err) } // looking for option args when starting App // like ./chat -addr=":3000" would start on this port var addr = flag.String("addr", ":8080", "App address") flag.Parse() // parse the flag // setting up gomniauth // creating random key http://godoc.org/github.com/stretchr/signature#RandomKey // in addition to gomniauth package we need to download: // go get github.com/clbanning/x2j // go get github.com/ugorji/go/codec // go get labix.org/v2/mgo/bson gomniauth.SetSecurityKey(signature.RandomKey(64)) gomniauth.WithProviders( facebook.New("key", "secret", "http://localhost:8080/auth/callback/facebook"), github.New("key", "secret", "http://localhost:8080/auth/callback/github"), google.New(configuration.GoogleKey, configuration.GoogleSecret, "http://localhost:8080/auth/callback/google"), ) r := newRoom() r.tracer = trace.New(os.Stdout) // HTTP handlers // wrapping /chat handler with MustAuth to enforce authentication http.Handle("/chat", MustAuth(&templateHandler{filename: "chat.html"})) http.Handle("/login", &templateHandler{filename: "login.html"}) // logout, deleting cookie data http.HandleFunc("/logout", func(w http.ResponseWriter, r *http.Request) { http.SetCookie(w, &http.Cookie{ Name: "auth", Value: "", Path: "/", MaxAge: -1, }) w.Header()["Location"] = []string{"/chat"} w.WriteHeader(http.StatusTemporaryRedirect) }) http.HandleFunc("/auth/", loginHandler) http.Handle("/room", r) http.Handle("/upload", &templateHandler{filename: "upload.html"}) http.HandleFunc("/uploader", uploadHandler) // servis static images // http.StripPrefix takes Handler in, modifies the path by removing // the specified prefix and passes functionality onto an inner // handler. Inner handler - http.FileServer servers static files, // provides index listing and generates 404 for missing objects // http.Dir function allows to specify exposed folders http.Handle("/avatars/", http.StripPrefix("/avatars/", http.FileServer(http.Dir("./avatars")))) // get the room going go r.run() // start the web server log.Println("Starting we server on ", *addr) if err := http.ListenAndServe(*addr, nil); err != nil { log.Fatal("ListenAndServe:", err) } }