本文整理汇总了Golang中net/http.Handler函数的典型用法代码示例。如果您正苦于以下问题:Golang Handler函数的具体用法?Golang Handler怎么用?Golang Handler使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Handler函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: router
func router() *mux.Router {
r := mux.NewRouter()
r.Handle("/tasks", http.Handler(ContextAdapter{ctx: taskctx, handler: ContextHandlerFunc(tasklist)})).Methods("GET")
r.Handle("/tasks", http.Handler(ContextAdapter{ctx: taskctx, handler: ContextHandlerFunc(taskadd)})).Methods("POST")
r.Handle("/tasks/complete", http.Handler(ContextAdapter{ctx: taskctx, handler: ContextHandlerFunc(taskcomplete)})).Methods("POST")
r.Handle("/tasks/search", http.Handler(ContextAdapter{ctx: taskctx, handler: ContextHandlerFunc(tasksearch)})).Methods("GET")
return r
}
示例2: UploadHandler
func UploadHandler(fileBackend backend.FileBackend) http.Handler {
result := func(w http.ResponseWriter, r *http.Request) {
log.Println("Uploading file...")
uploadedFile, header, err := r.FormFile("data")
if err != nil {
log.Printf("problem with file %v", err)
w.WriteHeader(http.StatusBadRequest)
return
}
defer uploadedFile.Close()
parts := s.Split(header.Filename, ".")
extension := parts[len(parts)-1]
contentType := mime.TypeByExtension("." + extension)
log.Printf("determined %s as content type", contentType)
log.Printf("got file %s", header.Filename)
id, err := fileBackend.Save(contentType, nil, uploadedFile)
if err != nil {
log.Printf("problem saving file %v", err)
w.WriteHeader(http.StatusInternalServerError)
}
w.Header().Set("Location", id)
w.WriteHeader(http.StatusCreated)
}
return http.Handler(http.HandlerFunc(result))
}
示例3: Run
func (a *Api) Run() error {
globalMux := http.NewServeMux()
router := mux.NewRouter()
router.HandleFunc("/", a.index).Methods("GET")
router.HandleFunc("/create", a.create).Methods("POST")
router.HandleFunc("/ip", a.getIP).Methods("GET")
router.HandleFunc("/state", a.getState).Methods("GET")
router.HandleFunc("/start", a.start).Methods("GET")
router.HandleFunc("/kill", a.kill).Methods("GET")
router.HandleFunc("/remove", a.remove).Methods("GET")
router.HandleFunc("/restart", a.restart).Methods("GET")
router.HandleFunc("/stop", a.stop).Methods("GET")
// enable auth if token is present
if a.config.AuthToken != "" {
am := auth.NewAuthMiddleware(a.config.AuthToken)
globalMux.Handle("/", negroni.New(
negroni.HandlerFunc(am.Handler),
negroni.Wrap(http.Handler(router)),
))
} else {
globalMux.Handle("/", router)
}
log.Infof("rivet version %s", version.FULL_VERSION)
log.Infof("listening: addr=%s", a.config.ListenAddr)
n := negroni.New()
n.UseHandler(globalMux)
return http.ListenAndServe(a.config.ListenAddr, n)
}
示例4: Run
func (app *App) Run() error {
path := "/"
if app.options.RandomUrl {
randomPath := generateRandomString(8)
path = "/" + randomPath + "/"
}
fs := http.StripPrefix(path, http.FileServer(&assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, Prefix: "bindata"}))
http.Handle(path, fs)
http.HandleFunc(path+"ws", app.handler)
endpoint := app.options.Address + ":" + app.options.Port
log.Printf("Server is running at %s, command: %s", endpoint+path, strings.Join(app.options.Command, " "))
handler := http.Handler(http.DefaultServeMux)
handler = loggerHandler(handler)
if app.options.Credential != "" {
handler = basicAuthHandler(handler, app.options.Credential)
}
err := http.ListenAndServe(endpoint, handler)
if err != nil {
return err
}
return nil
}
示例5: startHTTP
func startHTTP(wg *sync.WaitGroup) {
log.Println("Starting HTTP Server...")
mux := http.NewServeMux()
mux.HandleFunc("/status", statusHandler)
mux.HandleFunc("/ls", lsHandler)
mux.HandleFunc("/shutdown", func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprintf(w, "OK")
forceShutdown <- true
})
mux.Handle("/files/", http.StripPrefix("/files/", http.FileServer(torrentFS)))
handler := http.Handler(mux)
if config.idleTimeout > 0 {
connTrackChannel := make(chan int, 10)
handler = NewConnectionCounterHandler(connTrackChannel, mux)
go inactiveAutoShutdown(connTrackChannel)
}
log.Printf("Listening HTTP on %s...\n", config.bindAddress)
s := &http.Server{
Addr: config.bindAddress,
Handler: handler,
}
var e error
if httpListener, e = net.Listen("tcp", config.bindAddress); e != nil {
log.Fatal(e)
}
go s.Serve(httpListener)
defer wg.Done()
}
示例6: serve
func (e *Etcd) serve() (err error) {
var ctlscfg *tls.Config
if !e.cfg.ClientTLSInfo.Empty() {
plog.Infof("ClientTLS: %s", e.cfg.ClientTLSInfo)
if ctlscfg, err = e.cfg.ClientTLSInfo.ServerConfig(); err != nil {
return err
}
}
if e.cfg.CorsInfo.String() != "" {
plog.Infof("cors = %s", e.cfg.CorsInfo)
}
// Start the peer server in a goroutine
ph := v2http.NewPeerHandler(e.Server)
for _, l := range e.Peers {
go func(l net.Listener) {
e.errc <- servePeerHTTP(l, ph)
}(l)
}
// Start a client server goroutine for each listen address
ch := http.Handler(&cors.CORSHandler{
Handler: v2http.NewClientHandler(e.Server, e.Server.Cfg.ReqTimeout()),
Info: e.cfg.CorsInfo,
})
for _, sctx := range e.sctxs {
// read timeout does not work with http close notify
// TODO: https://github.com/golang/go/issues/9524
go func(s *serveCtx) {
e.errc <- s.serve(e.Server, ctlscfg, ch, e.errc)
}(sctx)
}
return nil
}
示例7: main
func main() {
var (
fsRoot = flag.String("fs.root", "/tmp", "FileSystem root directory")
httpAddress = flag.String("http.addr", ":5555", "HTTP listen address")
providerDir = flag.String("provider.dir", "/tmp", "Provider directory with bucket policies")
)
flag.Parse()
prometheus.Register("ent_requests_total", "Total number of requests made", prometheus.NilLabels, requestTotal)
prometheus.Register("ent_requests_duration_nanoseconds_total", "Total amount of time ent has spent to answer requests in nanoseconds", prometheus.NilLabels, requestDuration)
prometheus.Register("ent_requests_duration_nanoseconds", "Amounts of time ent has spent answering requests in nanoseconds", prometheus.NilLabels, requestDurations)
prometheus.Register("ent_request_bytes_total", "Total volume of request payloads emitted in bytes", prometheus.NilLabels, requestBytes)
prometheus.Register("ent_response_bytes_total", "Total volume of response payloads emitted in bytes", prometheus.NilLabels, responseBytes)
p, err := NewDiskProvider(*providerDir)
if err != nil {
log.Fatal(err)
}
fs := NewDiskFS(*fsRoot)
r := pat.New()
r.Get(fileRoute, handleGet(p, fs))
r.Post(fileRoute, handleCreate(p, fs))
r.Handle("/metrics", prometheus.DefaultRegistry.Handler())
r.Get("/", handleBucketList(p))
log.Fatal(http.ListenAndServe(*httpAddress, http.Handler(r)))
}
示例8: New
// New returns a new instance of GenericAPIServer from the given config.
// Certain config fields will be set to a default value if unset,
// including:
// ServiceClusterIPRange
// ServiceNodePortRange
// MasterCount
// ReadWritePort
// PublicAddress
// Public fields:
// Handler -- The returned GenericAPIServer has a field TopHandler which is an
// http.Handler which handles all the endpoints provided by the GenericAPIServer,
// including the API, the UI, and miscellaneous debugging endpoints. All
// these are subject to authorization and authentication.
// InsecureHandler -- an http.Handler which handles all the same
// endpoints as Handler, but no authorization and authentication is done.
// Public methods:
// HandleWithAuth -- Allows caller to add an http.Handler for an endpoint
// that uses the same authentication and authorization (if any is configured)
// as the GenericAPIServer's built-in endpoints.
// If the caller wants to add additional endpoints not using the GenericAPIServer's
// auth, then the caller should create a handler for those endpoints, which delegates the
// any unhandled paths to "Handler".
func (c completedConfig) New() (*GenericAPIServer, error) {
if c.Serializer == nil {
return nil, fmt.Errorf("Genericapiserver.New() called with config.Serializer == nil")
}
s := &GenericAPIServer{
ServiceClusterIPRange: c.ServiceClusterIPRange,
ServiceNodePortRange: c.ServiceNodePortRange,
LoopbackClientConfig: c.LoopbackClientConfig,
legacyAPIPrefix: c.APIPrefix,
apiPrefix: c.APIGroupPrefix,
admissionControl: c.AdmissionControl,
requestContextMapper: c.RequestContextMapper,
Serializer: c.Serializer,
minRequestTimeout: time.Duration(c.MinRequestTimeout) * time.Second,
enableSwaggerSupport: c.EnableSwaggerSupport,
MasterCount: c.MasterCount,
SecureServingInfo: c.SecureServingInfo,
InsecureServingInfo: c.InsecureServingInfo,
ExternalAddress: c.ExternalHost,
ClusterIP: c.PublicAddress,
PublicReadWritePort: c.ReadWritePort,
ServiceReadWriteIP: c.ServiceReadWriteIP,
ServiceReadWritePort: c.ServiceReadWritePort,
ExtraServicePorts: c.ExtraServicePorts,
ExtraEndpointPorts: c.ExtraEndpointPorts,
KubernetesServiceNodePort: c.KubernetesServiceNodePort,
apiGroupsForDiscovery: map[string]unversioned.APIGroup{},
enableOpenAPISupport: c.EnableOpenAPISupport,
openAPIInfo: c.OpenAPIInfo,
openAPIDefaultResponse: c.OpenAPIDefaultResponse,
openAPIDefinitions: c.OpenAPIDefinitions,
}
if c.RestfulContainer != nil {
s.HandlerContainer = c.RestfulContainer
} else {
s.HandlerContainer = NewHandlerContainer(http.NewServeMux(), c.Serializer)
}
// Use CurlyRouter to be able to use regular expressions in paths. Regular expressions are required in paths for example for proxy (where the path is proxy/{kind}/{name}/{*})
s.HandlerContainer.Router(restful.CurlyRouter{})
s.Mux = apiserver.NewPathRecorderMux(s.HandlerContainer.ServeMux)
apiserver.InstallServiceErrorHandler(s.Serializer, s.HandlerContainer)
if c.ProxyDialer != nil || c.ProxyTLSClientConfig != nil {
s.ProxyTransport = utilnet.SetTransportDefaults(&http.Transport{
Dial: c.ProxyDialer,
TLSClientConfig: c.ProxyTLSClientConfig,
})
}
s.installAPI(c.Config)
s.Handler, s.InsecureHandler = s.buildHandlerChains(c.Config, http.Handler(s.Mux.BaseMux().(*http.ServeMux)))
return s, nil
}
示例9: upsertMultiplePermissionsHandler
func upsertMultiplePermissionsHandler(mapper *pgmapper.Mapper, sidIdExtractor idextractor.Extractor) http.Handler {
result := func(w http.ResponseWriter, r *http.Request) {
sid, err := sidIdExtractor(r)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
ids, ok := r.URL.Query()["oid"]
if !ok {
w.WriteHeader(http.StatusBadRequest)
return
}
permissions := make(map[string]interface{})
err = json.NewDecoder(r.Body).Decode(&permissions)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
err = mapper.Execute("SELECT insert_bulk_sid_permissions(%v)", sid, permissions["create_permission"], permissions["read_permission"], permissions["update_permission"], permissions["delete_permission"], ids)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
return
}
return http.Handler(http.HandlerFunc(result))
}
示例10: main
func main() {
if !flag.Parsed() {
flag.Parse()
}
router := mux.NewRouter()
router.StrictSlash(true)
for _, route := range routes {
handler := http.Handler(http.HandlerFunc(route.HandlerFunc))
switch route.Type {
case "JSON":
handler = handlers.ContentTypeHandler(handler, "application/json")
case "":
break
default:
log.Fatalf("invalid route type: %v", route.Type)
}
r := router.NewRoute()
r.Name(route.Name).
Path(route.Path).
Methods(route.Methods).
Handler(handler)
}
address := fmt.Sprintf(":%d", *port)
handler := handlers.CombinedLoggingHandler(os.Stderr, router)
log.Printf("Version: %s", version.DeploymentManagerVersion)
log.Printf("Listening on port %d...", *port)
log.Fatal(http.ListenAndServe(address, handler))
}
示例11: main
func main() {
db := sqlx.MustConnect("sqlite3", ":memory:")
if err := createFooTable(db); err != nil {
log.Fatal("couldn't create table: ", err)
}
for i := 0; i < 10; i++ {
id, err := insertFoo(db, "hello world "+strconv.Itoa(i))
if err != nil {
log.Fatal("failed to insert value: ", err)
}
log.Print("inserted foo record ", id)
}
h := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fooListEndpoint(w, r, &FooStore{db: db})
}))
h = handlers.LoggingHandler(os.Stdout, h)
h = handlers.ContentTypeHandler(h, "application/json")
http.Handle("/foo/", h)
flag.Parse()
log.Print("starting http server on ", *addr)
if err := http.ListenAndServe(*addr, nil); err != nil {
log.Printf("http server failed: ", err)
}
}
示例12: Use
// Use adds a Middleware function to the stack.
func (b *Builder) Use(f Middleware) {
b.handler = http.Handler(nil)
b.middleware = append(b.middleware, f)
for i := len(b.middleware) - 1; i >= 0; i-- {
b.handler = b.middleware[i](b.handler)
}
}
示例13: upsertPermissionsHandler
func upsertPermissionsHandler(mapper *pgmapper.Mapper, objectIdExtractor idextractor.Extractor) http.Handler {
result := func(w http.ResponseWriter, r *http.Request) {
objectId, err := objectIdExtractor(r)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
ids, ok := r.URL.Query()["sid"]
entity := make(map[string]interface{})
err = json.NewDecoder(r.Body).Decode(&entity)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
if ok {
err = mapper.Execute("SELECT insert_bulk_permissions(%v)", objectId, entity["create_permission"], entity["read_permission"], entity["update_permission"], entity["delete_permission"], ids)
} else {
_, err = mapper.ExecuteRaw("insert into acl_entries(object_id,sid,create_permission,read_permission,update_permission,delete_permission) values($1,$2,$3,$4,$5,$6) ON CONFLICT (object_id,sid) DO UPDATE SET create_permission = $3, read_permission = $4, update_permission = $5, delete_permission = $6 where acl_entries.sid = $2 AND acl_entries.object_id = $1", objectId, entity["sid"], entity["create_permission"], entity["read_permission"], entity["update_permission"], entity["delete_permission"])
}
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
}
return http.Handler(http.HandlerFunc(result))
}
示例14: StartHttp
// StartHTTP starts listening for RPC requests sent via HTTP.
func StartHttp(cfg HttpConfig, codec codec.Codec, api shared.EthereumApi) error {
httpServerMu.Lock()
defer httpServerMu.Unlock()
addr := fmt.Sprintf("%s:%d", cfg.ListenAddress, cfg.ListenPort)
if httpServer != nil {
if addr != httpServer.Addr {
return fmt.Errorf("RPC service already running on %s ", httpServer.Addr)
}
return nil // RPC service already running on given host/port
}
// Set up the request handler, wrapping it with CORS headers if configured.
handler := http.Handler(&handler{codec, api})
if len(cfg.CorsDomain) > 0 {
opts := cors.Options{
AllowedMethods: []string{"POST"},
AllowedOrigins: strings.Split(cfg.CorsDomain, " "),
}
handler = cors.New(opts).Handler(handler)
}
// Start the server.
s, err := listenHTTP(addr, handler)
if err != nil {
glog.V(logger.Error).Infof("Can't listen on %s:%d: %v", cfg.ListenAddress, cfg.ListenPort, err)
return err
}
httpServer = s
return nil
}
示例15: TestRWVFS
func TestRWVFS(t *testing.T) {
tmpdir, err := ioutil.TempDir("", "rwvfs-test-")
if err != nil {
t.Fatal("TempDir", err)
}
defer os.RemoveAll(tmpdir)
h := http.Handler(rwvfs.HTTPHandler(rwvfs.Map(map[string]string{}), nil))
httpServer := httptest.NewServer(h)
defer httpServer.Close()
httpURL, err := url.Parse(httpServer.URL)
if err != nil {
t.Fatal(err)
}
tests := []struct {
fs rwvfs.FileSystem
path string
}{
{rwvfs.OS(tmpdir), "/foo"},
{rwvfs.Map(map[string]string{}), "/foo"},
{rwvfs.Sub(rwvfs.Map(map[string]string{}), "/x"), "/foo"},
{rwvfs.HTTP(httpURL, nil), "/foo"},
}
for _, test := range tests {
testWrite(t, test.fs, test.path)
testMkdir(t, test.fs)
testMkdirAll(t, test.fs)
testGlob(t, test.fs)
}
}