當前位置: 首頁>>代碼示例>>Golang>>正文


Golang mux.HandleFunc函數代碼示例

本文整理匯總了Golang中github.com/gorilla/mux.HandleFunc函數的典型用法代碼示例。如果您正苦於以下問題:Golang HandleFunc函數的具體用法?Golang HandleFunc怎麽用?Golang HandleFunc使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了HandleFunc函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: main

func main() {

	// Load the environment variables we need
	err := godotenv.Load()
	if err != nil {
		log.Fatal("Error loading .env file")
	}

	// Read the port
	port := os.Getenv("PORT")

	tlsConfig, err := getTLSConfig(os.Getenv("SWARM_CREDS_DIR"))
	if err != nil {
		log.Fatal("Could not create TLS certificate.")
	}

	docker, _ := dockerclient.NewDockerClient(os.Getenv("DOCKER_HOST"), tlsConfig)

	mux := mux.NewRouter()
	// mux.HandleFunc("/events", get_events(dbmap)).Methods("GET")
	// mux.HandleFunc("/events/{year}", get_events_by_year(dbmap)).Methods("GET")
	mux.HandleFunc("/spawn", spawn(docker)).Methods("GET")
	mux.HandleFunc("/list-containers", list_containers(docker)).Methods("GET")
	n := negroni.Classic()
	n.UseHandler(mux)
	log.Printf("Listening on port %s\n", port)
	n.Run(":" + port)

}
開發者ID:odewahn,項目名稱:thebe-server,代碼行數:29,代碼來源:main.go

示例2: Handler

// Handler uses a multiplexing router to route http requests
func (ws *webServer) Handler() http.Handler {
	mux := mux.NewRouter()

	mux.PathPrefix("/t/cc/").HandlerFunc(ws.Cloudconfig).Methods("GET")
	mux.PathPrefix("/t/ig/").HandlerFunc(ws.Ignition).Methods("GET")
	mux.PathPrefix("/t/bp/").HandlerFunc(ws.Bootparams).Methods("GET")

	mux.HandleFunc("/api/version", ws.Version)

	mux.HandleFunc("/api/nodes", ws.NodesList)
	mux.PathPrefix("/api/node/").HandlerFunc(ws.NodeFlags).Methods("GET")

	mux.PathPrefix("/api/flag/").HandlerFunc(ws.SetFlag).Methods("PUT")
	mux.PathPrefix("/api/flag/").HandlerFunc(ws.DelFlag).Methods("DELETE")

	mux.HandleFunc("/upload/", ws.Upload)
	mux.HandleFunc("/files", ws.Files).Methods("GET")
	mux.HandleFunc("/files", ws.DeleteFile).Methods("DELETE")
	mux.PathPrefix("/files/").Handler(http.StripPrefix("/files/",
		http.FileServer(http.Dir(filepath.Join(ws.ds.WorkspacePath(), "files")))))

	mux.PathPrefix("/ui/").Handler(http.FileServer(FS(false)))

	return mux
}
開發者ID:colonelmo,項目名稱:blacksmith,代碼行數:26,代碼來源:server.go

示例3: RouteRequest

func RouteRequest() http.Handler {
	mux := mux.NewRouter()
	mux.HandleFunc("/test", HandleTest)
	mux.HandleFunc("/json", HandleJSON)
	mux.HandleFunc("/retry", HandleRetry)
	mux.HandleFunc("/limit", HandleLimit)
	return mux
}
開發者ID:meshhq,項目名稱:gohttp,代碼行數:8,代碼來源:client_test.go

示例4: Start

func Start(c *Configuration) {
	log.Printf("Starting Deamon on Port: %s", c.Port)

	mux := mux.NewRouter()
	mux.HandleFunc("/bounce/{type}/{name}/{version}", http.HandlerFunc(bounce))
	mux.HandleFunc("/hook", http.HandlerFunc(hook))
	http.Handle("/", mux)

	log.Println("Listening...")
	http.ListenAndServe(":"+c.Port, nil)
}
開發者ID:samilton,項目名稱:bouncer,代碼行數:11,代碼來源:engine.go

示例5: NewServer

// Create a new server.
func NewServer(addr string, hooks ServerHooks, logger *log.Logger) *Server {
	srv := &Server{}
	srv.addr = addr
	srv.hooks = hooks
	srv.logger = logger
	mux := mux.NewRouter()
	mux.StrictSlash(true)
	mux.HandleFunc("/stop/", srv.handleStop).Methods("POST")
	mux.HandleFunc("/reload/", srv.handleReload).Methods("POST")
	srv.server = NewHTTPServer(addr, mux)
	return srv
}
開發者ID:zenreach,項目名稱:remotectl,代碼行數:13,代碼來源:server.go

示例6: tigertonicRouterFor

//
// Benchmarks for rcrowley/go-tigertonic's tigertonic.TrieServeMux:
//
func tigertonicRouterFor(namespaces []string, resources []string) http.Handler {
	mux := tigertonic.NewTrieServeMux()
	for _, ns := range namespaces {
		for _, res := range resources {
			mux.HandleFunc("GET", "/"+ns+"/"+res, helloHandler)
			mux.HandleFunc("POST", "/"+ns+"/"+res, helloHandler)
			mux.HandleFunc("GET", "/"+ns+"/"+res+"/{id}", helloHandler)
			mux.HandleFunc("POST", "/"+ns+"/"+res+"/{id}", helloHandler)
			mux.HandleFunc("DELETE", "/"+ns+"/"+res+"/{id}", helloHandler)
		}
	}
	return mux
}
開發者ID:rexk,項目名稱:golang-mux-benchmark,代碼行數:16,代碼來源:mux_bench_test.go

示例7: main

func main() {
	mux := mux.NewRouter().StrictSlash(true)

	mux.HandleFunc("/orders", GetOrders).Methods("GET")
	mux.HandleFunc("/orders/{orderId}/", GetOrder).Methods("GET")
	mux.HandleFunc("/orders/", PostOrder).Methods("POST")
	mux.HandleFunc("/orders/{orderId}/", DeleteOrder).Methods("DELETE")
	mux.HandleFunc("/orders/{orderId}/", PutOrder).Methods("PUT")

	log.Println("Listening...")
	log.Fatal(http.ListenAndServe(":3000", mux))

}
開發者ID:arscan,項目名稱:gosf,代碼行數:13,代碼來源:main.go

示例8: main

func main() {

	mux := mux.NewRouter()
	mux.HandleFunc("/", homeHandler)
	mux.HandleFunc("/data/{food}", dataHandler)
	mux.HandleFunc("/static/{folder}/{file}", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, r.URL.Path[1:])
	})

	port := ":3000"
	log.Println("Listening on " + port)
	http.ListenAndServe(port, mux)
}
開發者ID:charlieaustin,項目名稱:how-much-water,代碼行數:13,代碼來源:app.go

示例9: Mux

func (a *RestServer) Mux() *mux.Router {
	mux := mux.NewRouter()
	mux.HandleFunc("/api/nodes", a.nodesList)
	mux.HandleFunc("/api/etcd-endpoints", a.etcdEndpoints)

	mux.HandleFunc("/upload/", a.upload)
	mux.HandleFunc("/files", a.files).Methods("GET")
	mux.HandleFunc("/files", a.deleteFile).Methods("DELETE")
	mux.PathPrefix("/files/").Handler(http.StripPrefix("/files/", http.FileServer(http.Dir(filepath.Join(a.runtimeConfig.WorkspacePath, "files")))))
	mux.PathPrefix("/ui/").Handler(http.FileServer(FS(false)))

	return mux
}
開發者ID:alialaee,項目名稱:blacksmith,代碼行數:13,代碼來源:server.go

示例10: main

func main() {
	app := cli.App("System-healthcheck", "A service that report on current VM status at __health")

	hostPath = app.String(cli.StringOpt{
		Name:   "hostPath",
		Value:  "",
		Desc:   "The dir path of the mounted host fs (in the container)",
		EnvVar: "SYS_HC_HOST_PATH",
	})

	checks = append(checks, diskFreeChecker{20}.Checks()...)
	checks = append(checks, memoryChecker{15}.Checks()...)
	checks = append(checks, loadAverageChecker{}.Checks()...)
	checks = append(checks, ntpChecker{}.Checks()...)
	checks = append(checks, tcpChecker{}.Checks()...)

	mux := mux.NewRouter()
	mux.HandleFunc("/__health", fthealth.Handler("myserver", "a server", checks...))

	log.Printf("Starting http server on 8080\n")
	err := http.ListenAndServe(":8080", mux)
	if err != nil {
		panic(err)
	}
}
開發者ID:Financial-Times,項目名稱:coco-system-healthcheck,代碼行數:25,代碼來源:main.go

示例11: runServer

func runServer() *httptest.Server {
	handler := ShortenerHandler{Database: database}
	mux := mux.NewRouter().StrictSlash(true)
	mux.HandleFunc("/", handler.Add).Methods("POST")
	server := httptest.NewServer(mux)
	return server
}
開發者ID:gustavohenrique,項目名稱:gh1,代碼行數:7,代碼來源:handlers_test.go

示例12: startVulcan

// vulcan
func startVulcan() {
	mux := vulcan.NewMux()
	expr := fmt.Sprintf(`Method("%s") && Path("%s")`, "GET", "/hello")
	mux.HandleFunc(expr, helloHandler)

	http.ListenAndServe(":"+strconv.Itoa(port), mux)
}
開發者ID:cokeboL,項目名稱:go-web-framework-benchmark,代碼行數:8,代碼來源:server.go

示例13: ExampleServeMux_customized

func ExampleServeMux_customized() {
	// Define our error format and how to expose it to the client.
	type customError struct {
		Error    string `json:"error"`
		HTTPCode int    `json:"http_code"`
	}
	errorHandler := func(w ehttp.ResponseWriter, req *http.Request, err error) {
		_ = json.NewEncoder(w).Encode(customError{
			Error:    err.Error(),
			HTTPCode: w.Code(),
		})
	}

	// Define a cutom logger for unexpected events (double header send).
	logger := log.New(os.Stderr, "", log.LstdFlags)

	// Create the mux.
	mux := ehttp.NewServeMux(errorHandler, "application/text; charset=utf-8", false, logger)

	// Register the handler.
	mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) error {
		// Return an error.
		return ehttp.NewErrorf(http.StatusTeapot, "fail")
	})

	// Start serve the mux.
	log.Fatal(http.ListenAndServe(":8080", mux))
}
開發者ID:agrarianlabs,項目名稱:localdiscovery,代碼行數:28,代碼來源:example_test.go

示例14: ExampleServeMux_panic

func ExampleServeMux_panic() {
	mux := ehttp.NewServeMux(nil, "application/text; charset=utf-8", true, nil)
	mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) error {
		panic(ehttp.InternalServerError)
	})
	log.Fatal(http.ListenAndServe(":8080", mux))
}
開發者ID:agrarianlabs,項目名稱:localdiscovery,代碼行數:7,代碼來源:example_test.go

示例15: startTestDriver

func startTestDriver() error {
	mux := http.NewServeMux()
	server := httptest.NewServer(mux)
	if server == nil {
		return fmt.Errorf("Failed to start a HTTP Server")
	}

	mux.HandleFunc("/Plugin.Activate", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
		fmt.Fprintf(w, `{"Implements": ["%s"]}`, driverapi.NetworkPluginEndpointType)
	})

	mux.HandleFunc(fmt.Sprintf("/%s.GetCapabilities", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
		fmt.Fprintf(w, `{"Scope":"global"}`)
	})

	mux.HandleFunc(fmt.Sprintf("/%s.CreateNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
		fmt.Fprintf(w, "null")
	})

	mux.HandleFunc(fmt.Sprintf("/%s.DeleteNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
		fmt.Fprintf(w, "null")
	})

	mux.HandleFunc(fmt.Sprintf("/%s.CreateEndpoint", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
		fmt.Fprintf(w, "null")
	})

	mux.HandleFunc(fmt.Sprintf("/%s.DeleteEndpoint", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
		fmt.Fprintf(w, "null")
	})

	mux.HandleFunc(fmt.Sprintf("/%s.Join", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
		fmt.Fprintf(w, "null")
	})

	mux.HandleFunc(fmt.Sprintf("/%s.Leave", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
		fmt.Fprintf(w, "null")
	})

	if err := os.MkdirAll("/etc/docker/plugins", 0755); err != nil {
		return err
	}

	if err := ioutil.WriteFile("/etc/docker/plugins/test.spec", []byte(server.URL), 0644); err != nil {
		return err
	}

	return nil
}
開發者ID:rcgoodfellow,項目名稱:libnetwork,代碼行數:57,代碼來源:dnet.go


注:本文中的github.com/gorilla/mux.HandleFunc函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。