Example #1
1
// ServeHTTP dispatches the handler registered in the matched route.
//
// When there is a match, the route variables can be retrieved calling
// mux.Vars(request).
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	// Clean path to canonical form and redirect.
	if p := cleanPath(req.URL.Path); p != req.URL.Path {

		// Added 3 lines (Philip Schlump) - It was dropping the query string and #whatever from query.
		// This matches with fix in go 1.2 r.c. 4 for same problem.  Go Issue:
		// http://code.google.com/p/go/issues/detail?id=5252
		url := *req.URL
		url.Path = p
		p = url.String()

		w.Header().Set("Location", p)
		w.WriteHeader(http.StatusMovedPermanently)
		return
	}
	var match RouteMatch
	var handler http.Handler
	if r.Match(req, &match) {
		handler = match.Handler
		setVars(req, match.Vars)
		setCurrentRoute(req, match.Route)
	}
	if handler == nil {
		handler = r.NotFoundHandler
		if handler == nil {
			handler = http.NotFoundHandler()
		}
	}
	if !r.KeepContext {
		defer context.Clear(req)
	}
	handler.ServeHTTP(w, req)
}
Example #2
0
// Creates a GorillaMux router containing the HTTP handlers for a server.
func createHandler(sc *serverContext) http.Handler {
	r := mux.NewRouter()
	r.StrictSlash(true)
	// Global operations:
	r.Handle("/", makeHandler(sc, (*handler).handleRoot)).Methods("GET", "HEAD")
	r.Handle("/_all_dbs", makeHandler(sc, (*handler).handleAllDbs)).Methods("GET", "HEAD")

	if len(sc.databases) == 1 {
		// If there is exactly one database we can handle the standard /_session by just redirecting
		// it to that database's _session handler.
		for _, db := range sc.databases {
			path := "/" + db.dbcontext.Name
			r.Handle("/_session", http.RedirectHandler(path+"/_session", http.StatusTemporaryRedirect))
			r.Handle("/_persona", http.RedirectHandler(path+"/_persona", http.StatusTemporaryRedirect))
		}
	} else {
		r.Handle("/_session", http.NotFoundHandler())
		r.Handle("/_persona", http.NotFoundHandler())
	}

	// Operations on databases:
	r.Handle("/{newdb}/", makeHandler(sc, (*handler).handleCreateDB)).Methods("PUT")
	r.Handle("/{db}/", makeHandler(sc, (*handler).handleGetDB)).Methods("GET", "HEAD")
	r.Handle("/{db}/", makeHandler(sc, (*handler).handleDeleteDB)).Methods("DELETE")
	r.Handle("/{db}/", makeHandler(sc, (*handler).handlePostDoc)).Methods("POST")

	// Special database URLs:
	dbr := r.PathPrefix("/{db}/").Subrouter()
	dbr.Handle("/_all_docs", makeHandler(sc, (*handler).handleAllDocs)).Methods("GET", "HEAD", "POST")
	dbr.Handle("/_bulk_docs", makeHandler(sc, (*handler).handleBulkDocs)).Methods("POST")
	dbr.Handle("/_bulk_get", makeHandler(sc, (*handler).handleBulkGet)).Methods("GET", "HEAD")
	dbr.Handle("/_changes", makeHandler(sc, (*handler).handleChanges)).Methods("GET", "HEAD")
	dbr.Handle("/_design/sync_gateway", makeHandler(sc, (*handler).handleDesign)).Methods("GET", "HEAD")
	dbr.Handle("/_ensure_full_commit", makeHandler(sc, (*handler).handleEFC)).Methods("POST")
	dbr.Handle("/_revs_diff", makeHandler(sc, (*handler).handleRevsDiff)).Methods("POST")

	// Session/login URLs are per-database (unlike in CouchDB)
	dbr.Handle("/_session", makeAdminHandler(sc, (*handler).handleSessionGET)).Methods("GET", "HEAD")
	dbr.Handle("/_session", makeAdminHandler(sc, (*handler).handleSessionPOST)).Methods("POST")
	if sc.config.Persona != nil {
		dbr.Handle("/_persona", makeAdminHandler(sc, (*handler).handlePersonaPOST)).Methods("POST")
	}

	// Document URLs:
	dbr.Handle("/_local/{docid}", makeHandler(sc, (*handler).handleGetLocalDoc)).Methods("GET", "HEAD")
	dbr.Handle("/_local/{docid}", makeHandler(sc, (*handler).handlePutLocalDoc)).Methods("PUT")
	dbr.Handle("/_local/{docid}", makeHandler(sc, (*handler).handleDelLocalDoc)).Methods("DELETE")

	dbr.Handle("/{docid}", makeHandler(sc, (*handler).handleGetDoc)).Methods("GET", "HEAD")
	dbr.Handle("/{docid}", makeHandler(sc, (*handler).handlePutDoc)).Methods("PUT")
	dbr.Handle("/{docid}", makeHandler(sc, (*handler).handleDeleteDoc)).Methods("DELETE")

	dbr.Handle("/{docid}/{attach}", makeHandler(sc, (*handler).handleGetAttachment)).Methods("GET", "HEAD")

	// Fallbacks that have to be added last:
	r.PathPrefix("/").Methods("OPTIONS").Handler(makeHandler(sc, (*handler).handleOptions))
	r.PathPrefix("/").Handler(makeHandler(sc, (*handler).handleBadRoute))

	return r
}
Example #3
0
// nodeHandler handles requests for '/api/<version>/nodes/<system_id>/'.
func nodeHandler(server *TestServer, w http.ResponseWriter, r *http.Request, systemId string, operation string) {
	node, ok := server.nodes[systemId]
	if !ok {
		http.NotFoundHandler().ServeHTTP(w, r)
		return
	}
	UUID, UUIDError := node.values["system_id"].GetString()

	if r.Method == "GET" {
		if operation == "" {
			w.WriteHeader(http.StatusOK)
			if UUIDError == nil {
				i, err := JSONObjectFromStruct(server.client, server.nodeMetadata[UUID].Interfaces)
				checkError(err)
				if err == nil {
					node.values["interface_set"] = i
				}
			}
			fmt.Fprint(w, marshalNode(node))
			return
		} else if operation == "details" {
			if UUIDError == nil {
				i, err := JSONObjectFromStruct(server.client, server.nodeMetadata[UUID].Interfaces)
				if err == nil {
					node.values["interface_set"] = i
				}
			}
			nodeDetailsHandler(server, w, r, systemId)
			return
		} else {
			w.WriteHeader(http.StatusBadRequest)
			return
		}
	}
	if r.Method == "POST" {
		// The only operations supported are "start", "stop" and "release".
		if operation == "start" || operation == "stop" || operation == "release" {
			// Record operation on node.
			server.addNodeOperation(systemId, operation, r)

			if operation == "release" {
				delete(server.OwnedNodes(), systemId)
			}

			w.WriteHeader(http.StatusOK)
			fmt.Fprint(w, marshalNode(node))
			return
		}

		w.WriteHeader(http.StatusBadRequest)
		return
	}
	if r.Method == "DELETE" {
		delete(server.nodes, systemId)
		w.WriteHeader(http.StatusOK)
		return
	}
	http.NotFoundHandler().ServeHTTP(w, r)
}
// spacesHandler handles requests for '/api/<version>/spaces/'.
func spacesHandler(server *TestServer, w http.ResponseWriter, r *http.Request) {
	var err error
	spacesURLRE := regexp.MustCompile(`/spaces/(.+?)/`)
	spacesURLMatch := spacesURLRE.FindStringSubmatch(r.URL.Path)
	spacesURL := getSpacesEndpoint(server.version)

	var ID uint
	var gotID bool
	if spacesURLMatch != nil {
		ID, err = NameOrIDToID(spacesURLMatch[1], server.spaceNameToID, 1, uint(len(server.spaces)))

		if err != nil {
			http.NotFoundHandler().ServeHTTP(w, r)
			return
		}

		gotID = true
	}

	switch r.Method {
	case "GET":
		w.Header().Set("Content-Type", "application/vnd.api+json")
		if len(server.spaces) == 0 {
			// Until a space is registered, behave as if the endpoint
			// does not exist. This way we can simulate older MAAS
			// servers that do not support spaces.
			http.NotFoundHandler().ServeHTTP(w, r)
			return
		}

		if r.URL.Path == spacesURL {
			var spaces []Space
			for i := uint(1); i < server.nextSpace; i++ {
				s, ok := server.spaces[i]
				if ok {
					spaces = append(spaces, s)
				}
			}
			err = json.NewEncoder(w).Encode(spaces)
		} else if gotID == false {
			w.WriteHeader(http.StatusBadRequest)
		} else {
			err = json.NewEncoder(w).Encode(server.spaces[ID])
		}
		checkError(err)
	case "POST":
		//server.NewSpace(r.Body)
	case "PUT":
		//server.UpdateSpace(r.Body)
	case "DELETE":
		delete(server.spaces, ID)
		w.WriteHeader(http.StatusOK)
	default:
		w.WriteHeader(http.StatusBadRequest)
	}
}
Example #5
0
func TestRouterEventHandler(t *testing.T) {
	routes := make(map[string]bool)
	routes["GET /api/v1/settings"] = false
	routes["GET /api/v1/group1/hello"] = false
	routes["GET /api/v1/group1/group2/hello"] = false
	routes["GET /api/v1/apps/:app/clients/users/:userid/info"] = false
	routes["OPTIONS /api/v1/settings"] = false
	routes["HEAD /api/v1/settings"] = false
	routes["DELETE /api/v1/settings"] = false
	routes["POST /api/v1/settings"] = false
	routes["PUT /api/v1/settings"] = false
	routes["PATCH /api/v1/settings"] = false
	routes["NotFound"] = false
	routes["MethodNotAllowed"] = false

	r := New()
	r.EventHandler(func(evt Event) {
		switch e := evt.(type) {
		case AddHandlerEvent:
			routes[e.Method+" "+e.Path] = true
			// t.Logf("%s %s", e.Method, e.Path)
		case NotFoundHandlerEvent:
			routes["NotFound"] = true
		case MethodNotAllowedHandlerEvent:
			routes["MethodNotAllowed"] = true
		}
	})
	r.NotFound(http.NotFoundHandler())
	r.MethodNotAllowed(http.NotFoundHandler())

	// api group
	api := r.Group("/api/v1")
	api.GET("/settings", GetTest)
	api.OPTIONS("/settings", OptionsTest)
	api.HEAD("/settings", HeadTest)
	api.DELETE("/settings", DeleteTest)
	api.POST("/settings", PostTest)
	api.PUT("/settings", PutTest)
	api.PATCH("/settings", PatchTest)

	// Create router group and handler
	group1 := api.Group("/group1")
	group1.GET("/hello", GetTest)

	// Create nested group and route
	group2 := group1.Group("/group2")
	group2.GET("/hello", GetTest)

	appGroup := api.Group("/apps/:app")
	clientGroup := appGroup.Group("/clients")
	clientGroup.GET("/users/:userid/info", GetTest)

	for k, v := range routes {
		assert.True(t, v, "%s should be true", k)
	}
}
Example #6
0
func releaseIPAddressHandler(server *TestServer, w http.ResponseWriter, r *http.Request, ip string) {
	if netIP := net.ParseIP(ip); netIP == nil {
		http.NotFoundHandler().ServeHTTP(w, r)
		return
	}
	if server.RemoveIPAddress(ip) {
		w.WriteHeader(http.StatusOK)
		return
	}
	http.NotFoundHandler().ServeHTTP(w, r)
}
Example #7
0
// deviceHandler handles requests for '/api/<version>/devices/<system_id>/'.
func deviceHandler(server *TestServer, w http.ResponseWriter, r *http.Request, systemId string, operation string) {
	device, ok := server.devices[systemId]
	if !ok {
		http.NotFoundHandler().ServeHTTP(w, r)
		return
	}
	if r.Method == "GET" {
		deviceJSON := renderDevice(device)
		if operation == "" {
			w.WriteHeader(http.StatusOK)
			fmt.Fprint(w, deviceJSON)
			return
		} else {
			w.WriteHeader(http.StatusBadRequest)
			return
		}
	}
	if r.Method == "POST" {
		if operation == "claim_sticky_ip_address" {
			err := r.ParseForm()
			checkError(err)
			values := r.PostForm
			// TODO(mfoord): support optional mac_address parameter
			// TODO(mfoord): requested_address should be optional
			// and we should generate one if it isn't provided.
			address, hasAddress := getValue(values, "requested_address")
			if !hasAddress {
				w.WriteHeader(http.StatusBadRequest)
				return
			}
			checkError(err)
			device.IPAddresses = append(device.IPAddresses, address)
			deviceJSON := renderDevice(device)
			w.WriteHeader(http.StatusOK)
			fmt.Fprint(w, deviceJSON)
			return
		} else {
			w.WriteHeader(http.StatusBadRequest)
			return
		}
	} else if r.Method == "DELETE" {
		delete(server.devices, systemId)
		w.WriteHeader(http.StatusNoContent)
		return

	}

	// TODO(mfoord): support PUT method for updating device
	http.NotFoundHandler().ServeHTTP(w, r)
}
Example #8
0
func main() {
	http.HandleFunc("/", index)
	http.HandleFunc("/login", login)
	http.Handle("/favicon.ico", http.NotFoundHandler())

	http.ListenAndServe(":8000", nil)
}
Example #9
0
func main(){
	http.Handle("/favicon.ico",http.NotFoundHandler())
	http.HandleFunc("/",func(res http.ResponseWriter,req *http.Request){
		cookie, err := req.Cookie("session-id")
		if err == http.ErrNoCookie{
			id, _ := uuid.NewV4()
			cookie = &http.Cookie{
				Name: "session-id",
				Value: id.String(),
				HttpOnly:true,
			}
		}

		if(req.FormValue("name") != "" && !strings.Contains(cookie.Value, "name")){
			cookie.Value = cookie.Value + `name= ` + req.FormValue("name")
		}

		http.SetCookie(res, cookie)
		io.WriteString(res,`<!DOCTYPE html>
		<html>
		  <body>
		    <form method="POST">
		    `+cookie.Value+`
		      <br/>
		      <input type="text" name="name">
		      <input type="submit">
		    </form>
		  </body>
		</html>`)
	})
	http.ListenAndServe(":8080",nil)
}
Example #10
0
func init() {
	http.HandleFunc("/", handleIndex)
	http.HandleFunc("/put", handlePut)
	http.HandleFunc("/get", handleGet)
	http.Handle("/favicon.ico", http.NotFoundHandler())
	http.Handle("/public/", http.StripPrefix("/public", http.FileServer(http.Dir("public/"))))
}
Example #11
0
func main() {
	http.Handle("/favicon.ico", http.NotFoundHandler())
	http.HandleFunc("/", homepage)
	http.HandleFunc("/show", show)

	http.ListenAndServe("localhost:8080", nil)
}
Example #12
0
func main() {
	http.HandleFunc("/", serve)
	http.Handle("/favicon.ico", http.NotFoundHandler())

	log.Println("Listening...")
	http.ListenAndServe(":8080", nil)
}
Example #13
0
func Example() {
	// Set up an HTTP server
	listener, err := net.Listen("tcp", ":80")
	if err != nil {
		os.Exit(1)
	}

	// app.Serve is a shortcut for using the listener as a closer and calling Serve()
	app.Serve(listener, &http.Server{
		Handler: http.NotFoundHandler(), //example, use real handler
	})

	// You can run one-time tasks too with app.Go
	app.Go(func() error {
		if !registerMyselfSomewhere() {
			return errors.New("Registration failed. Shutting down...")
		}
		return nil
	})

	setupHeartbeat()

	// main will wait for all goroutines to complete and then run closers.
	app.Main()
}
Example #14
0
func jsonflowsAPIRequest(w http.ResponseWriter, r *http.Request) {
	err := r.ParseForm()
	if err != nil {
		http.NotFoundHandler().ServeHTTP(w, r)
	}
	flowIDStr := r.FormValue("flowID")
	if flowIDStr == "" {
		x := jsonflowsSendAll()
		fmt.Fprintf(w, "%s", x)
		return
	}

	flowID, err := strconv.ParseUint(flowIDStr, 10, 64)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		fmt.Fprintf(w, "Invalid flowID")
		return
	}
	fi, err := flowTracker.GetFlow(flowID)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		fmt.Fprintf(w, "Invalid flowID")
		return
	}
	fmt.Fprintf(w, "{%s}", fi.JSON())
}
Example #15
0
func init() {
	r := httprouter.New()
	http.Handle("/", r)
	r.GET("/", home)
	r.GET("/following", fing)
	r.GET("/followingme", fingme)
	r.GET("/user/:user", user)
	r.GET("/form/login", login)
	r.GET("/form/signup", signup)
	r.POST("/api/checkusername", checkUserName)
	r.POST("/api/createuser", createUser)
	r.POST("/api/login", loginProcess)
	r.POST("/api/tweet", tweetProcess)
	r.GET("/api/logout", logout)
	r.GET("/api/follow/:user", follow)
	r.GET("/api/unfollow/:user", unfollow)
	http.Handle("/favicon.ico", http.NotFoundHandler())
	http.Handle("/public/", http.StripPrefix("/public", http.FileServer(http.Dir("public/"))))

	tpl = template.New("roottemplate")
	tpl = tpl.Funcs(template.FuncMap{
		"humanize_time": humanize.Time,
	})

	tpl = template.Must(tpl.ParseGlob("templates/html/*.html"))
}
Example #16
0
func main() {
	tpl, _ = template.ParseGlob("templates/html/*.html")
	http.HandleFunc("/", home)
	http.Handle("/favicon.ico", http.NotFoundHandler())
	http.Handle("/public/", http.StripPrefix("/public", http.FileServer(http.Dir("public/"))))
	http.ListenAndServe(":8080", nil)
}
Example #17
0
func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())

	err := os.Chdir(path.Join(path.Dir(os.Args[0]), ".."))
	if err != nil {
		log.Fatal(err)
	}

	flag.Parse()

	pathTable = string_table.NewPreallocated(*pathHashtableSize)

	http.HandleFunc("/", index)
	http.HandleFunc("/collect", collect)
	http.HandleFunc("/bucket/", bucketIndex)
	http.HandleFunc("/server/", serverIndex)
	http.HandleFunc("/stats", stats)

	http.Handle("/favicon.ico", http.NotFoundHandler())

	go updater(rx)

	err = http.ListenAndServe(fmt.Sprintf("%s:%d", *host, *port), nil)
	if err != nil {
		log.Fatal(err)
	}
}
Example #18
0
func TestProxy(t *testing.T) {
	goodOrigin := buildOrigin(false)
	defer goodOrigin.Close()
	prematureCloser := buildOrigin(true)
	defer prematureCloser.Close()

	server := httptest.NewServer(filters.Join(
		New(&Options{
			IdleTimeout: 500 * time.Second,
			OnRequest: func(req *http.Request) {
				req.Header.Set(fakeRequestHeader, "faker")
			},
			OnResponse: func(resp *http.Response) *http.Response {
				// Add fake response header
				resp.Header.Set(fakeResponseHeader, "fakeresp")
				return resp
			},
		}),
		filters.Adapt(http.NotFoundHandler())))
	defer server.Close()

	doTestProxy(t, goodOrigin, server, false)
	doTestProxy(t, goodOrigin, server, true)
	doTestProxy(t, prematureCloser, server, false)
	doTestProxy(t, prematureCloser, server, true)
}
Example #19
0
func init() {
	router := httprouter.New()
	router.GET("/", showList)
	router.POST("/", updateList)
	http.Handle("/", router)
	http.Handle("/favicon.ico", http.NotFoundHandler())
}
Example #20
0
func TestReportStats(t *testing.T) {
	md, nr := startWithMockReporter()
	defer md.Stop()
	var remoteAddr atomic.Value

	// start server with byte counting
	l, err := net.Listen("tcp", "127.0.0.1:0")
	if !assert.NoError(t, err, "Listen should not fail") {
		return
	}

	// large enough interval so it will only report stats in Close()
	ml := md.Listener(l, 10*time.Second)
	s := http.Server{
		Handler: http.NotFoundHandler(),
		ConnState: func(c net.Conn, s http.ConnState) {
			if s == http.StateClosed {
				remoteAddr.Store(c.RemoteAddr().String())
			}
		},
	}
	go func() { _ = s.Serve(ml) }()

	time.Sleep(100 * time.Millisecond)
	// start client with byte counting
	c := http.Client{
		Transport: &http.Transport{
			// carefully chosen interval to report another once before Close()
			Dial: md.Dialer(net.Dial, 160*time.Millisecond),
		},
	}
	req, _ := http.NewRequest("GET", "http://"+l.Addr().String(), nil)
	resp, _ := c.Do(req)
	assert.Equal(t, 404, resp.StatusCode)

	// Close without reading from body, to force server to close connection
	_ = resp.Body.Close()
	time.Sleep(100 * time.Millisecond)
	nr.Lock()
	defer nr.Unlock()
	t.Logf("Traffic entries: %+v", nr.traffic)
	if assert.Equal(t, 2, len(nr.traffic)) {
		ct := nr.traffic[l.Addr().String()]
		st := nr.traffic[remoteAddr.Load().(string)]

		if assert.NotNil(t, ct) {
			assert.Equal(t, 0, int(ct.MinOut), "client stats should only report increased byte count")
			assert.Equal(t, 0, int(ct.MinIn), "client stats should only report increased byte count")
			assert.Equal(t, 96, int(ct.MaxOut), "client stats should only report increased byte count")
			assert.Equal(t, 176, int(ct.MaxIn), "client stats should only report increased byte count")
			assert.Equal(t, 96, int(ct.TotalOut), "client stats should only report increased byte count")
			assert.Equal(t, 176, int(ct.TotalIn), "client stats should only report increased byte count")
		}

		if assert.NotNil(t, st) {
			assert.Equal(t, ct.TotalOut, st.TotalIn, "should report server stats with bytes in")
			assert.Equal(t, ct.TotalIn, st.TotalOut, "should report server stats with bytes out")
		}
	}
}
Example #21
0
func newGroupcacheHTTPHandler() http.Handler {
	mux := http.NewServeMux()
	mux.Handle("/", newGroupcacheHTTPPool())
	mux.HandleFunc("/stats", groupcacheStatsHTTPHandler)
	mux.Handle("/favicon.ico", http.NotFoundHandler())
	return mux
}
Example #22
0
func main() {
	http.Handle("/favicon.ico", http.NotFoundHandler())
	http.HandleFunc("/name", formshow)
	http.HandleFunc("/", formsubmit)

	http.ListenAndServe("localhost:8080", nil)
}
Example #23
0
// ipAddressesHandler handles requests for '/api/<version>/ipaddresses/'.
func ipAddressesHandler(server *TestServer, w http.ResponseWriter, r *http.Request) {
	err := r.ParseForm()
	checkError(err)
	values := r.Form
	op := values.Get("op")

	switch r.Method {
	case "GET":
		if op != "" {
			panic("expected empty op for GET, got " + op)
		}
		listIPAddressesHandler(server, w, r)
		return
	case "POST":
		switch op {
		case "reserve":
			reserveIPAddressHandler(server, w, r, values.Get("network"), values.Get("requested_address"))
			return
		case "release":
			releaseIPAddressHandler(server, w, r, values.Get("ip"))
			return
		default:
			panic("expected op=release|reserve for POST, got " + op)
		}
	}
	http.NotFoundHandler().ServeHTTP(w, r)
}
Example #24
0
// ServeHTTP dispatches the handler registered in the matched route.
//
// When there is a match, the route variables can be retrieved calling
// mux.Vars(request).
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	// Clean path to canonical form and redirect.
	if p := cleanPath(req.URL.Path); p != req.URL.Path {
		w.Header().Set("Location", p)
		w.WriteHeader(http.StatusMovedPermanently)
		return
	}
	var match RouteMatch
	var handler http.Handler
	if r.Match(req, &match) {
		handler = match.Handler
		setVars(req, match.Vars)
		setCurrentRoute(req, match.Route)
	}
	if handler == nil {
		if r.NotFoundHandler == nil {
			r.NotFoundHandler = http.NotFoundHandler()
		}
		handler = r.NotFoundHandler
	}
	if !r.KeepContext {
		defer context.Clear(req)
	}
	handler.ServeHTTP(w, req)
}
Example #25
0
func main() {
	rooms.OnMiss(func(roomname string) (lrucache.Cacheable, error) {
		if verbose {
			log.Printf("Created room %q", roomname)
		}
		return newChatroom(BACKLOG_SIZE), nil
	})
	http.HandleFunc("/", handler)
	addr := flag.String("l", "localhost:8081", "listen address")
	flag.BoolVar(&verbose, "v", false, "verbose")
	root := flag.String("root", "", "(optional) root dir for web requests")
	flag.Parse()
	if *root != "" {
		files = http.FileServer(http.Dir(*root))
	} else {
		files = http.NotFoundHandler()
	}
	if verbose {
		log.Print("Starting websocket groupchat server on ", *addr)
	}
	err := http.ListenAndServe(*addr, nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
Example #26
0
func init() {
	http.HandleFunc("/", handler)
	http.Handle("/favicon.ico", http.NotFoundHandler())
	http.Handle("/css/", http.StripPrefix("/css", http.FileServer(http.Dir("css/"))))
	http.Handle("/img/", http.StripPrefix("/img", http.FileServer(http.Dir("img/"))))
	tpl = template.Must(template.ParseGlob("*.html"))
}
Example #27
0
func jsonpSendHandler(r *Router, w http.ResponseWriter, req *http.Request) {
	if xhrProlog(w, req) {
		return
	}
	w.Header().Set("Content-type", "text/plain; charset=UTF-8")
	sessionId := mux.Vars(req)["sessionid"]
	// Find the session
	s := r.getSession(sessionId)
	if s == nil {
		http.NotFoundHandler().ServeHTTP(w, req)
		return
	}
	xhrJsessionid(r, w, req)

	payload, err := extractSendContent(req)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	if len(payload) == 0 {
		http.Error(w, EmptyPayload.Error(), http.StatusInternalServerError)
		return
	}
	err = s.fromClient(message(payload))
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	io.WriteString(w, "ok")
}
Example #28
0
func main() {
	http.Handle("/favicon.ico", http.NotFoundHandler())
	http.HandleFunc("/", rootPage)
	http.HandleFunc("/login", loginPage)
	http.HandleFunc("/logout", logoutPage)
	http.ListenAndServe(":8080", nil)
}
Example #29
0
func init() {
	http.Handle("/favicon.ico", http.NotFoundHandler())
	http.HandleFunc("/", makeHandler(indexHandler))
	http.HandleFunc("/roles", makeHandler(rolesHandler))
	http.HandleFunc("/userSettings", makeHandler(userSettingsHandler))
	http.HandleFunc("/accountSettings", makeHandler(accountSettingsHandler))
	// http.HandleFunc("/signUp", makeHandler(signUpHandler))
	// http.HandleFunc("/logIn", makeHandler(logInHandler))
	// http.HandleFunc("/accounts", makeHandler(accountsHandler))
	// http.HandleFunc("/accounts/", makeHandler(accountHandler))
	http.HandleFunc("/logOut", makeHandler(logOutHandler))
	/* if http.PostForm("/logIn", data); err != nil {
		http.Err(w, "Internal server error while login",
			http.StatusBadRequest)
	} */
	fs := http.FileServer(http.Dir("static"))
	http.Handle("/css/", fs)
	http.Handle("/img/", fs)
	http.Handle("/js/", fs)
	/* log.Printf("About to listen on 10443. " +
	"Go to https://192.168.1.100:10443/ " +
	"or https://localhost:10443/") */
	// Redirecting to a port or a domain etc.
	// go http.ListenAndServe(":8080",
	// http.RedirectHandler("https://192.168.1.100:10443", 301))
	// err := http.ListenAndServeTLS(":10443", "cert.pem", "key.pem", nil)
	// ListenAndServeTLS always returns a non-nil error !!!
	// log.Fatal(err)
}
Example #30
0
func main() {
	http.HandleFunc("/", index)
	http.Handle("/favicon.ico", http.NotFoundHandler())
	fs := http.FileServer(http.Dir("assets"))
	http.Handle("/imgs/", fs)
	http.ListenAndServe(":8080", nil)
}