本文整理汇总了Golang中github.com/gorilla/mux.HandleFunc函数的典型用法代码示例。如果您正苦于以下问题:Golang HandleFunc函数的具体用法?Golang HandleFunc怎么用?Golang HandleFunc使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了HandleFunc函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
示例16: 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/machines", ws.MachinesList)
mux.HandleFunc("/api/machines/{mac}", ws.MachineDelete).Methods("DELETE")
// mux.PathPrefix("/api/machine/").HandlerFunc(ws.NodeSetIPMI).Methods("PUT")
// Machine variables; used in templates
mux.PathPrefix("/api/machines/{mac}/variables").HandlerFunc(ws.MachineVariables).Methods("GET")
mux.PathPrefix("/api/machines/{mac}/variables/{name}").HandlerFunc(ws.SetMachineVariable).Methods("PUT")
mux.PathPrefix("/api/machines/{mac}/variables/{name}").HandlerFunc(ws.DelMachineVariable).Methods("DELETE")
// Cluster variables; used in templates
mux.PathPrefix("/api/variables/{name}").HandlerFunc(ws.GetClusterVariables).Methods("GET")
mux.PathPrefix("/api/variables/{name}").HandlerFunc(ws.SetClusterVariables).Methods("PUT")
mux.PathPrefix("/api/variables/{name}").HandlerFunc(ws.DelClusterVariables).Methods("DELETE")
mux.PathPrefix("/api/variables").HandlerFunc(ws.ClusterVariablesList).Methods("GET")
// TODO: returning other files functionalities
mux.PathPrefix("/files/images/").Handler(http.StripPrefix("/files/images",
http.FileServer(http.Dir(filepath.Join(ws.ds.WorkspacePath(), "images")))))
mux.PathPrefix("/files/").Handler(http.StripPrefix("/files/",
http.FileServer(http.Dir(filepath.Join(ws.ds.WorkspacePath(), "files")))))
mux.Path("/ui").Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/ui/", 302)
}))
mux.PathPrefix("/ui/").Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
index, _ := FSByte(false, "/static/index.html")
w.Write(index)
}))
mux.PathPrefix("/static/").Handler(http.FileServer(FS(false)))
mux.PathPrefix("/uploadworkspace/{hash}").HandlerFunc(ws.WorkspaceUploadHandler).Methods("POST")
return mux
}
开发者ID:cafebazaar,项目名称:blacksmith,代码行数:47,代码来源:server.go
示例17: loadTigerTonic
func loadTigerTonic(routes []route) http.Handler {
re := regexp.MustCompile(":([^/]*)")
mux := tigertonic.NewTrieServeMux()
for _, route := range routes {
mux.HandleFunc(route.method, re.ReplaceAllString(route.path, "{$1}"), httpHandlerFunc)
}
return mux
}
开发者ID:lamproae,项目名称:go-http-routing-benchmark,代码行数:8,代码来源:routers.go
示例18: main
func main() {
handlers := BaseHandlers()
mux := mux.NewRouter()
mux.HandleFunc("/", handlers.landing)
mux.HandleFunc("/signup", handlers.signup)
accounts := mux.PathPrefix("/account").Subrouter()
accounts.HandleFunc("/", handlers.accountIndex)
n := negroni.Classic()
n.UseHandler(mux)
n.Run(*httpAddr)
}
开发者ID:JesseObrien,项目名称:dietary,代码行数:17,代码来源:main.go
示例19: main
func main() {
mux := mux.NewRouter()
mux.HandleFunc("/", rootHandler)
muxWithMiddlewares := http.TimeoutHandler(mux, time.Second*39, "Timeout!")
http.ListenAndServe(":18080", muxWithMiddlewares)
}
开发者ID:szqh97,项目名称:test,代码行数:8,代码来源:mux_t.go
示例20: main
func main() {
configtoml := flag.String("f", "nixy.toml", "Path to config. (default nixy.toml)")
version := flag.Bool("v", false, "prints current nixy version")
flag.Parse()
if *version {
fmt.Println(VERSION)
os.Exit(0)
}
file, err := ioutil.ReadFile(*configtoml)
if err != nil {
log.Fatal(err)
}
err = toml.Unmarshal(file, &config)
if err != nil {
log.Fatal("Problem parsing config: ", err)
}
if config.Statsd != "" {
statsd, _ = g2s.Dial("udp", config.Statsd)
}
nixystats := stats.New()
//mux := http.NewServeMux()
mux := mux.NewRouter()
mux.HandleFunc("/", nixy_version)
mux.HandleFunc("/v1/reload", nixy_reload)
mux.HandleFunc("/v1/apps", nixy_apps)
mux.HandleFunc("/v1/health", nixy_health)
mux.HandleFunc("/v1/stats", func(w http.ResponseWriter, req *http.Request) {
stats := nixystats.Data()
b, _ := json.MarshalIndent(stats, "", " ")
w.Write(b)
return
})
handler := nixystats.Handler(mux)
s := &http.Server{
Addr: ":" + config.Port,
Handler: handler,
}
eventStream()
eventWorker()
log.Println("Starting nixy on :" + config.Port)
err = s.ListenAndServe()
if err != nil {
log.Fatal(err)
}
}
开发者ID:abhishekamralkar,项目名称:nixy,代码行数:45,代码来源:nixy.go
注:本文中的github.com/gorilla/mux.HandleFunc函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论