func (rp *NativeReverseProxy) Initialize(rpConfig ReverseProxyConfig) (string, error) { var err error rp.ReverseProxyConfig = rpConfig rp.listener, err = net.Listen("tcp", rpConfig.Listen) if err != nil { return "", err } rp.server = manners.NewWithServer(&http.Server{Handler: rp}) rp.dialer = &net.Dialer{ Timeout: rp.DialTimeout, KeepAlive: 30 * time.Second, } rp.Transport = http.Transport{ Dial: rp.dialer.Dial, TLSHandshakeTimeout: rp.DialTimeout, MaxIdleConnsPerHost: 100, } rp.rp = &httputil.ReverseProxy{ Director: noopDirector, Transport: rp, FlushInterval: rp.FlushInterval, BufferPool: &bufferPool{}, } return rp.listener.Addr().String(), nil }
// Run is called to start the web service. func Run(host string, routes http.Handler, readTimeout, writeTimeout time.Duration) error { // Create a new server and set timeout values. server := manners.NewWithServer(&http.Server{ Addr: host, Handler: routes, ReadTimeout: readTimeout, WriteTimeout: writeTimeout, MaxHeaderBytes: 1 << 20, }) go func() { // Listen for an interrupt signal from the OS. osSignals := make(chan os.Signal) signal.Notify(osSignals, os.Interrupt) <-osSignals // Shut down the API server. server.Close() }() return server.ListenAndServe() }
func runServer(c *cli.Context) { listener, err := net.Listen("tcp", c.String("listen")) if err != nil { log.Fatal(err) } router := Router{ ReadRedisHost: c.String("read-redis-host"), ReadRedisPort: c.Int("read-redis-port"), WriteRedisHost: c.String("write-redis-host"), WriteRedisPort: c.Int("write-redis-port"), LogPath: c.String("access-log"), RequestTimeout: time.Duration(c.Int("request-timeout")) * time.Second, DialTimeout: time.Duration(c.Int("dial-timeout")) * time.Second, DeadBackendTTL: c.Int("dead-backend-time"), FlushInterval: time.Duration(c.Int("flush-interval")) * time.Millisecond, } err = router.Init() if err != nil { log.Fatal(err) } s := manners.NewWithServer(&http.Server{Handler: &router}) handleSignals(s) log.Printf("Listening on %v...\n", listener.Addr()) err = s.Serve(listener) router.Stop() if err != nil { log.Fatal(err) } }
// Runs HTTP server func (wh *WorkerHttp) Run(wg *sync.WaitGroup, die chan bool) { defer wg.Done() server := manners.NewWithServer(&http.Server{ Addr: wh.addr, Handler: wh.getRouter(), }) // Start goroutine which will gracefully close server go func(server *manners.GracefulServer) { for { select { case <-die: logger.Instance(). Info("Stopping HTTP server") server.Close() return default: } time.Sleep(time.Second) } }(server) logger.Instance(). WithField("addr", server.Addr). Info("HTTP server started") _ = server.ListenAndServe() }
func (hd *HealthD) startHttpServer(hostPort string) { server := manners.NewWithServer(&http.Server{ Addr: hostPort, Handler: hd.apiRouter(), }) hd.stopHTTP = server.Close server.ListenAndServe() }
// Run starts the server func (s *Server) Run(log *logrus.Entry) error { s.log = log.WithField("app", AppName) // Init the app s.InitStart(log) s.gracefulServer = manners.NewWithServer(s.httpServer(s.log)) return s.gracefulServer.ListenAndServe() }
// Start initializes and starts the web server func Start() { srv = &Server{} srv.Router = mux.NewRouter() srv.Server = manners.NewWithServer(&http.Server{ Addr: ":8080", Handler: srv.Router, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20, }) log.Printf("Starting Server v%s ...", meta.App.Version) api.InitAPI(srv.Router) startShutdownListener() srv.Server.ListenAndServe() }
func main() { shutdown := make(chan int) //create a notification channel to shutdown sigChan := make(chan os.Signal, 1) //start the main http server for serving traffic router := httprouter.New() router.GET("/", hello) server := manners.NewWithServer(&http.Server{Addr: ":80", Handler: router}) go func() { server.ListenAndServe() shutdown <- 1 }() //start the system server for health checks and shutdowns s := &status{ ready: false, } hRouter := httprouter.New() hRouter.GET("/ready", makeReady(s)) hRouter.GET("/prestop", makePrestop(s)) go func() { http.ListenAndServe(":8080", hRouter) }() //register for interupt (Ctrl+C) and SIGTERM (docker) signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM) go func() { <-sigChan fmt.Println("Shutting down...") server.Close() }() //move server to ready state s.Lock() s.ready = true s.Unlock() <-shutdown }
func main() { // Initialize common startup setting common.Startup() // Load configs config := common.LoadGlobConfigs("config.*.yaml") // common.MergeConfigFromConsul(config) // Initialize store handler storeHandler, err := frontend.NewStoreHandler() if err != nil { log.Fatalf("Initialize store handler failed: %s", err) } apiMux := http.NewServeMux() apiMux.Handle("/store/", storeHandler) apiHandler := http.Handler(apiMux) rootMux := http.NewServeMux() rootMux.Handle("/_health", frontend.NewHealthCheckHandler()) rootMux.Handle("/_version", frontend.NewVersionHandler()) rootMux.Handle("/", apiHandler) log.Printf("Starting HTTP listener on %s...", config.GetString("http.endpoint")) httpServer := manners.NewWithServer( &http.Server{ Addr: config.GetString("http.endpoint"), Handler: rootMux, }) // Listen for signals and do graceful shutdown sigCh := make(chan os.Signal, 1) signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM) go func() { <-sigCh log.Printf("Shutting down...") // Stop catching signals, so that we can actually stop on second signal signal.Stop(sigCh) atomic.StoreInt32(&frontend.Shutdown, 1) // Slow down shutdown to get some extra time for graceful restart log.Printf("Sleeping...") time.Sleep(common.ParseDuration(config.GetString("shutdown.sleep"))) log.Printf("Done sleeping!") // Shutdown HTTP httpServer.Close() }() var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() err := httpServer.ListenAndServe() if err != nil { log.Fatalf("Listen error: %s", err) } }() wg.Wait() }
func (app *App) Run() error { if app.options.PermitWrite { log.Printf("Permitting clients to write input to the PTY.") } if app.options.Once { log.Printf("Once option is provided, accepting only one client") } path := "" if app.options.EnableRandomUrl { path += "/" + generateRandomString(app.options.RandomUrlLength) } endpoint := "" if app.options.EnalbeRandomPort { laddr := net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 0} l, err := net.ListenTCP("tcp4", &laddr) if err != nil { log.Printf("Get wrong random port.") return err } addr := l.Addr() endpoint = net.JoinHostPort(app.options.Address, strconv.Itoa(addr.(*net.TCPAddr).Port)) } else { endpoint = net.JoinHostPort(app.options.Address, app.options.Port) } wsHandler := http.HandlerFunc(app.handleWS) customIndexHandler := http.HandlerFunc(app.handleCustomIndex) authTokenHandler := http.HandlerFunc(app.handleAuthToken) staticHandler := http.FileServer( &assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, Prefix: "static"}, ) var siteMux = http.NewServeMux() if app.options.IndexFile != "" { log.Printf("Using index file at " + app.options.IndexFile) siteMux.Handle(path+"/", customIndexHandler) } else { siteMux.Handle(path+"/", http.StripPrefix(path+"/", staticHandler)) } siteMux.Handle(path+"/auth_token.js", authTokenHandler) siteMux.Handle(path+"/js/", http.StripPrefix(path+"/", staticHandler)) siteMux.Handle(path+"/favicon.png", http.StripPrefix(path+"/", staticHandler)) siteHandler := http.Handler(siteMux) if app.options.EnableBasicAuth { log.Printf("Using Basic Authentication") siteHandler = wrapBasicAuth(siteHandler, app.options.Credential) } wsMux := http.NewServeMux() wsMux.Handle("/", siteHandler) wsMux.Handle(path+"/ws", wsHandler) siteHandler = (http.Handler(wsMux)) siteHandler = wrapLogger(siteHandler) scheme := "http" if app.options.EnableTLS { scheme = "https" } log.Printf( "Server is starting with command: %s", strings.Join(app.command, " "), ) if app.options.Address != "" { log.Printf( "URL: %s", (&url.URL{Scheme: scheme, Host: endpoint, Path: path + "/"}).String(), ) } else { if app.options.EnalbeRandomPort { randomPort := strings.Split(endpoint, ":")[1] for _, address := range listAddresses() { log.Printf( "URL: %s", (&url.URL{ Scheme: scheme, Host: net.JoinHostPort(address, randomPort), Path: path + "/", }).String(), ) } } else { for _, address := range listAddresses() { log.Printf( "URL: %s", (&url.URL{ Scheme: scheme, Host: net.JoinHostPort(address, app.options.Port), Path: path + "/", }).String(), ) } } } var err error app.server = manners.NewWithServer( &http.Server{Addr: endpoint, Handler: siteHandler}, ) if app.options.EnableTLS { crtFile := ExpandHomeDir(app.options.TLSCrtFile) keyFile := ExpandHomeDir(app.options.TLSKeyFile) log.Printf("TLS crt file: " + crtFile) log.Printf("TLS key file: " + keyFile) err = app.server.ListenAndServeTLS(crtFile, keyFile) } else { err = app.server.ListenAndServe() } if err != nil { return err } log.Printf("Exiting...") return nil }
func New(svr *http.Server, sigs []os.Signal) *server { return &server{ m: manners.NewWithServer(svr), sigs: sigs, } }
func (app *App) Run() error { if app.options.PermitWrite { log.Printf("Permitting clients to write input to the PTY.") } if app.options.Once { log.Printf("Once option is provided, accepting only one client") } path := "" if app.options.EnableRandomUrl { path += "/" + generateRandomString(app.options.RandomUrlLength) } endpoint := net.JoinHostPort(app.options.Address, app.options.Port) wsHandler := http.HandlerFunc(app.handleWS) customIndexHandler := http.HandlerFunc(app.handleCustomIndex) authTokenHandler := http.HandlerFunc(app.handleAuthToken) staticHandler := http.FileServer( &assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, Prefix: "static"}, ) var siteMux = http.NewServeMux() if app.options.IndexFile != "" { log.Printf("Using index file at " + app.options.IndexFile) siteMux.Handle(path+"/", customIndexHandler) } else { siteMux.Handle(path+"/", http.StripPrefix(path+"/", staticHandler)) } siteMux.Handle(path+"/auth_token.js", authTokenHandler) siteMux.Handle(path+"/js/", http.StripPrefix(path+"/", staticHandler)) siteMux.Handle(path+"/favicon.png", http.StripPrefix(path+"/", staticHandler)) siteHandler := http.Handler(siteMux) if app.options.EnableBasicAuth { log.Printf("Using Basic Authentication") siteHandler = wrapBasicAuth(siteHandler, app.options.Credential) } wsMux := http.NewServeMux() wsMux.Handle("/", siteHandler) wsMux.Handle(path+"/ws", wsHandler) siteHandler = (http.Handler(wsMux)) siteHandler = wrapLogger(siteHandler) scheme := "http" if app.options.EnableTLS { scheme = "https" } log.Printf( "Server is starting with command: %s", strings.Join(app.command, " "), ) if app.options.Address != "" { log.Printf( "URL: %s", (&url.URL{Scheme: scheme, Host: endpoint, Path: path + "/"}).String(), ) } else { for _, address := range listAddresses() { log.Printf( "URL: %s", (&url.URL{ Scheme: scheme, Host: net.JoinHostPort(address, app.options.Port), Path: path + "/", }).String(), ) } } serverMaker := func() *http.Server { return &http.Server{ Addr: endpoint, Handler: siteHandler} } if app.options.VerifyClientCert && app.options.EnableTLS { serverMaker = func() *http.Server { clientCaPool := x509.NewCertPool() for _, path := range app.options.ClientCAs { pem, err := ioutil.ReadFile(path) if err != nil { log.Printf("Could not read pem file at: " + path) return nil } if clientCaPool.AppendCertsFromPEM(pem) { log.Printf("Could not parse pem file at: " + path) return nil } } return &http.Server{ Addr: endpoint, Handler: siteHandler, TLSConfig: &tls.Config{ ClientAuth: tls.RequireAndVerifyClientCert, ClientCAs: clientCaPool, PreferServerCipherSuites: true}} } } server := serverMaker() if server == nil { log.Printf("Failed to build server.") return errors.New("Failed to build server.") } var err error app.server = manners.NewWithServer( server, ) if app.options.EnableTLS { crtFile := ExpandHomeDir(app.options.TLSCrtFile) keyFile := ExpandHomeDir(app.options.TLSKeyFile) log.Printf("TLS crt file: " + crtFile) log.Printf("TLS key file: " + keyFile) err = app.server.ListenAndServeTLS(crtFile, keyFile) } else { err = app.server.ListenAndServe() } if err != nil { return err } log.Printf("Exiting...") return nil }
func run() error { var staticHandler http.Handler if GlobalOpt.Once { glog.V(3).Infof("Once option is provided, accepting only one client") } endpoint := net.JoinHostPort(GlobalOpt.Address, GlobalOpt.Port) staticHandler = http.FileServer( &assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, Prefix: "static"}) var siteMux = http.NewServeMux() siteMux.Handle("/", staticHandler) siteMux.Handle("/auth_token.js", http.HandlerFunc(daemon.handleAuthToken)) if GlobalOpt.Debug { staticHandler = http.HandlerFunc(resourcesHandler) } siteMux.Handle("/js/", staticHandler) siteMux.Handle("/css/", staticHandler) siteMux.Handle("/font/", staticHandler) siteMux.Handle("/favicon.ico", staticHandler) //add demo handler if GlobalOpt.DemoEnable { siteMux.HandleFunc("/demo/", demoHandler) siteMux.HandleFunc("/cmd", demoCmdHandler) } siteHandler := http.Handler(siteMux) if GlobalOpt.EnableBasicAuth { glog.V(3).Infof("Using Basic Authentication") siteHandler = wrapBasicAuth(siteHandler, GlobalOpt.Credential) } wsMux := http.NewServeMux() wsMux.Handle("/", wrapHeaders(siteHandler)) wsMux.Handle("/ws", http.HandlerFunc(wsHandler)) siteHandler = wrapLogger(http.Handler(wsMux)) scheme := "http" if GlobalOpt.EnableTLS { scheme = "https" } /* glog.Infof( "Server is starting with command: %s\n", strings.Join(session.command, " ") ) */ if GlobalOpt.Address != "" { glog.V(0).Infof( "URL: %s", (&url.URL{Scheme: scheme, Host: endpoint, Path: "/"}).String(), ) } else { for _, address := range listAddresses() { glog.V(0).Infof( "URL: %s", (&url.URL{ Scheme: scheme, Host: net.JoinHostPort(address, GlobalOpt.Port), Path: "/", }).String(), ) } } server, err := makeServer(daemon, endpoint, &siteHandler) if err != nil { return errors.New("Failed to build server: " + err.Error()) } daemon.server = manners.NewWithServer(server) if GlobalOpt.EnableTLS { crtFile := expandHomeDir(GlobalOpt.TLSCrtFile) keyFile := expandHomeDir(GlobalOpt.TLSKeyFile) glog.V(0).Infof("TLS crt file: " + crtFile) glog.V(0).Infof("TLS key file: " + keyFile) err = daemon.server.ListenAndServeTLS(crtFile, keyFile) } else { err = daemon.server.ListenAndServe() } if err != nil { return err } glog.V(0).Infof("Exiting...") return nil }
func run() error { if GlobalOpt.Once { glog.V(3).Infof("Once option is provided, accepting only one client") } path := "" if GlobalOpt.EnableRandomUrl { path += "/" + generateRandomString(GlobalOpt.RandomUrlLength) } endpoint := net.JoinHostPort(GlobalOpt.Address, GlobalOpt.Port) customIndexHandler := http.HandlerFunc(daemon.handleCustomIndex) authTokenHandler := http.HandlerFunc(daemon.handleAuthToken) staticHandler := http.FileServer( &assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, Prefix: "static"}, ) var siteMux = http.NewServeMux() if GlobalOpt.IndexFile != "" { glog.V(3).Infof("Using index file at " + GlobalOpt.IndexFile) siteMux.Handle(path+"/", customIndexHandler) } else { siteMux.Handle(path+"/", http.StripPrefix(path+"/", staticHandler)) } siteMux.Handle(path+"/auth_token.js", authTokenHandler) siteMux.Handle(path+"/js/", http.StripPrefix(path+"/", staticHandler)) siteMux.Handle(path+"/favicon.png", http.StripPrefix(path+"/", staticHandler)) siteHandler := http.Handler(siteMux) if GlobalOpt.EnableBasicAuth { glog.V(3).Infof("Using Basic Authentication") siteHandler = wrapBasicAuth(siteHandler, GlobalOpt.Credential) } siteHandler = wrapHeaders(siteHandler) wsMux := http.NewServeMux() wsMux.Handle("/", siteHandler) wsMux.Handle(path+"/ws", http.HandlerFunc(wsHandler)) siteHandler = wrapLogger(http.Handler(wsMux)) scheme := "http" if GlobalOpt.EnableTLS { scheme = "https" } /* glog.Infof( "Server is starting with command: %s\n", strings.Join(session.command, " ") ) */ if GlobalOpt.Address != "" { glog.V(0).Infof( "URL: %s", (&url.URL{Scheme: scheme, Host: endpoint, Path: path + "/"}).String(), ) } else { for _, address := range listAddresses() { glog.V(0).Infof( "URL: %s", (&url.URL{ Scheme: scheme, Host: net.JoinHostPort(address, GlobalOpt.Port), Path: path + "/", }).String(), ) } } server, err := makeServer(daemon, endpoint, &siteHandler) if err != nil { return errors.New("Failed to build server: " + err.Error()) } daemon.server = manners.NewWithServer(server) if GlobalOpt.EnableTLS { crtFile := expandHomeDir(GlobalOpt.TLSCrtFile) keyFile := expandHomeDir(GlobalOpt.TLSKeyFile) glog.V(0).Infof("TLS crt file: " + crtFile) glog.V(0).Infof("TLS key file: " + keyFile) err = daemon.server.ListenAndServeTLS(crtFile, keyFile) } else { err = daemon.server.ListenAndServe() } if err != nil { return err } glog.V(0).Infof("Exiting...") return nil }
func (app *App) Run() error { if app.options.PermitWrite { log.Printf("Permitting clients to write input to the PTY.") } if app.options.Once { log.Printf("Once option is provided, accepting only one client") } path := "" if app.options.EnableRandomUrl { path += "/" + generateRandomString(app.options.RandomUrlLength) } endpoint := net.JoinHostPort(app.options.Address, app.options.Port) wsHandler := http.HandlerFunc(app.handleWS) customIndexHandler := http.HandlerFunc(app.handleCustomIndex) authTokenHandler := http.HandlerFunc(app.handleAuthToken) staticHandler := http.FileServer( &assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, Prefix: "static"}, ) var siteMux = http.NewServeMux() if app.options.IndexFile != "" { log.Printf("Using index file at " + app.options.IndexFile) siteMux.Handle(path+"/", customIndexHandler) } else { siteMux.Handle(path+"/", http.StripPrefix(path+"/", staticHandler)) } siteMux.Handle(path+"/auth_token.js", authTokenHandler) siteMux.Handle(path+"/js/", http.StripPrefix(path+"/", staticHandler)) siteMux.Handle(path+"/favicon.png", http.StripPrefix(path+"/", staticHandler)) siteHandler := http.Handler(siteMux) if app.options.EnableBasicAuth { log.Printf("Using Basic Authentication") siteHandler = wrapBasicAuth(siteHandler, app.options.Credential) } siteHandler = wrapHeaders(siteHandler) wsMux := http.NewServeMux() wsMux.Handle("/", siteHandler) wsMux.Handle(path+"/ws", wsHandler) siteHandler = (http.Handler(wsMux)) siteHandler = wrapLogger(siteHandler) scheme := "http" if app.options.EnableTLS { scheme = "https" } log.Printf( "Server is starting with command: %s", strings.Join(app.command, " "), ) if app.options.Address != "" { log.Printf( "URL: %s", (&url.URL{Scheme: scheme, Host: endpoint, Path: path + "/"}).String(), ) } else { for _, address := range listAddresses() { log.Printf( "URL: %s", (&url.URL{ Scheme: scheme, Host: net.JoinHostPort(address, app.options.Port), Path: path + "/", }).String(), ) } } server, err := app.makeServer(endpoint, &siteHandler) if err != nil { return errors.New("Failed to build server: " + err.Error()) } app.server = manners.NewWithServer( server, ) if app.options.EnableTLS { crtFile := ExpandHomeDir(app.options.TLSCrtFile) keyFile := ExpandHomeDir(app.options.TLSKeyFile) log.Printf("TLS crt file: " + crtFile) log.Printf("TLS key file: " + keyFile) err = app.server.ListenAndServeTLS(crtFile, keyFile) } else { err = app.server.ListenAndServe() } if err != nil { return err } log.Printf("Exiting...") return nil }
func (app *App) Run() error { if app.options.PermitWrite { log.Printf("Permitting clients to write input to the PTY.") } path := "" if app.options.EnableRandomUrl { path += "/" + generateRandomString(app.options.RandomUrlLength) } endpoint := net.JoinHostPort(app.options.Address, app.options.Port) wsHandler := http.HandlerFunc(app.handleWS) staticHandler := http.FileServer( &assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, Prefix: "static"}, ) if app.options.Once { log.Printf("Once option is provided, accepting only one client") } var siteMux = http.NewServeMux() if app.options.IndexFile != "" { log.Printf("Using index file at " + app.options.IndexFile) indexHandler := http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, ExpandHomeDir(app.options.IndexFile)) }, ) siteMux.Handle(path+"/", indexHandler) } else { siteMux.Handle(path+"/", http.StripPrefix(path+"/", staticHandler)) } siteMux.Handle(path+"/js/", http.StripPrefix(path+"/", staticHandler)) siteMux.Handle(path+"/favicon.png", http.StripPrefix(path+"/", staticHandler)) siteMux.Handle(path+"/ws", wsHandler) siteHandler := http.Handler(siteMux) if app.options.EnableBasicAuth { log.Printf("Using Basic Authentication") siteHandler = wrapBasicAuth(siteHandler, app.options.Credential) } siteHandler = wrapLogger(siteHandler) scheme := "http" if app.options.EnableTLS { scheme = "https" } log.Printf( "Server is starting with command: %s", strings.Join(app.command, " "), ) if app.options.Address != "" { log.Printf( "URL: %s", (&url.URL{Scheme: scheme, Host: endpoint, Path: path + "/"}).String(), ) } else { for _, address := range listAddresses() { log.Printf( "URL: %s", (&url.URL{ Scheme: scheme, Host: net.JoinHostPort(address, app.options.Port), Path: path + "/", }).String(), ) } } var err error app.server = manners.NewWithServer( &http.Server{Addr: endpoint, Handler: siteHandler}, ) if app.options.EnableTLS { err = app.server.ListenAndServeTLS( ExpandHomeDir(app.options.TLSCrtFile), ExpandHomeDir(app.options.TLSKeyFile), ) } else { err = app.server.ListenAndServe() } if err != nil { return err } log.Printf("Exiting...") return nil }
func (app *App) Run() error { if app.options.PermitWrite { log.Printf("Permitting clients to write input to the PTY.") } path := "" if app.options.RandomUrl { path += "/" + generateRandomString(8) } endpoint := net.JoinHostPort(app.options.Address, app.options.Port) wsHandler := http.HandlerFunc(app.handleWS) staticHandler := http.FileServer( &assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, Prefix: "static"}, ) if app.options.Once { log.Printf("Once option is provided, accepting only one client") wsHandler = wrapOnce(wsHandler, app) } var siteMux = http.NewServeMux() siteMux.Handle(path+"/", http.StripPrefix(path+"/", staticHandler)) siteMux.Handle(path+"/ws", wsHandler) siteHandler := http.Handler(siteMux) if app.options.Credential != "" { log.Printf("Using Basic Authentication") siteHandler = wrapBasicAuth(siteHandler, app.options.Credential) } siteHandler = wrapLogger(siteHandler) scheme := "http" if app.options.EnableTLS { scheme = "https" } log.Printf( "Server is starting with command: %s", strings.Join(app.options.Command, " "), ) if app.options.Address != "" { log.Printf( "URL: %s", (&url.URL{Scheme: scheme, Host: endpoint, Path: path + "/"}).String(), ) } else { for _, address := range listAddresses() { log.Printf( "URL: %s", (&url.URL{ Scheme: scheme, Host: net.JoinHostPort(address, app.options.Port), Path: path + "/", }).String(), ) } } var err error app.server = manners.NewWithServer( &http.Server{Addr: endpoint, Handler: siteHandler}, ) if app.options.EnableTLS { cert, key := app.loadTLSFiles() err = app.server.ListenAndServeTLS(cert, key) } else { err = app.server.ListenAndServe() } if err != nil { return err } log.Printf("Exiting...") return nil }
func GetUserToken(client_id string, client_secret string, socket string) (string, error) { mux := http.NewServeMux() result := make(chan string) error := make(chan error) redirect_uri := "http://" + socket + "/oauth" mux.HandleFunc("/oauth", func(w http.ResponseWriter, r *http.Request) { code := r.URL.Query().Get("code") if code == "" { w.WriteHeader(400) fmt.Fprintln(w, "You must specify code in querystring. Probably Oauth error...") } v := url.Values{} v.Set("client_id", client_id) v.Set("client_secret", client_secret) v.Set("grant_type", "authorization_code") v.Set("redirect_uri", redirect_uri) v.Set("code", code) resp, err := http.PostForm("https://api.twitch.tv/kraken/oauth2/token", v) if err != nil { error <- err } contents, err := ioutil.ReadAll(resp.Body) if err != nil { error <- err } var tokenResp TokenResponse err2 := json.Unmarshal(contents, &tokenResp) if err2 != nil { error <- err2 } w.Write([]byte("we got the token, close this now")) result <- tokenResp.AccessToken }) mux.HandleFunc("/authorize", func(w http.ResponseWriter, r *http.Request) { v := url.Values{} v.Set("client_id", client_id) v.Set("response_type", "code") v.Set("redirect_uri", redirect_uri) v.Set("scope", "user_read") url := "https://api.twitch.tv/kraken/oauth2/authorize?" + v.Encode() http.Redirect(w, r, url, 302) }) s := manners.NewWithServer(&http.Server{ Addr: socket, Handler: mux, }) defer s.Close() go func() { fmt.Println("Visit http://" + socket + "/authorize to get a key") s.ListenAndServe() }() select { case r := <-result: return r, nil case e := <-error: return "", e } }