// BytesHandler returns n random bytes of binary data and accepts an
// optional 'seed' integer query parameter.
358098
func BytesHandler(w http.ResponseWriter, r *http.Request) {
	n, _ := strconv.Atoi(mux.Vars(r)["n"]) // shouldn't fail due to route pattern

	seedStr := r.URL.Query().Get("seed")
	if seedStr == "" {
		seedStr = fmt.Sprintf("%d", time.Now().UnixNano())
	}

	seed, _ := strconv.ParseInt(seedStr, 10, 64) // shouldn't fail due to route pattern
	rnd := rand.New(rand.NewSource(seed))
	buf := make([]byte, BinaryChunkSize)
	for n > 0 {
		rnd.Read(buf) // will never return err
		if n >= len(buf) {
			n -= len(buf)
			w.Write(buf)
		} else {
			// last chunk
			w.Write(buf[:n])
			break
		}
	}
}
464900
func (ss *StaticServer) FilesHandler(fileNames ...string) http.Handler {

	// todo: cache concatenated files on disk and serve from there.

	mimeType := ss.mimeType(fileNames[0])
	var buf []byte
	var openErr error

	for _, fileName := range fileNames {
		p, err := ioutil.ReadFile(ss.resolve(fileName))
		if err != nil {
			openErr = err
			buf = nil
			break
		}
		buf = append(buf, p...)
	}

	id := strings.Join(fileNames, " ")

	return &staticHandler{
		ss: ss,
		id: func(_ string) string { return id },
		open: func(p string) (io.ReadCloser, int64, string, error) {
			return ioutil.NopCloser(bytes.NewReader(buf)), int64(len(buf)), mimeType, openErr
		},
	}
}
145520
func pingHandler(w http.ResponseWriter, _ *http.Request) {
	w.Header().Set(CONTENTTYPE, TEXTPLAIN)
	w.Write([]byte(PINGRESPONSE))
}
926592
func (r *FlatChain) ChainHandler(h http.Handler) FlatChains {
	fh := FlatChainHandlerWrap(h, r.log)
	r.Chain(fh)
	return fh
}
974363
func FileHandler(path string, fmtr Format) (Handler, error) {
	f, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
	if err != nil {
		return nil, err
	}
	return closingHandler{f, StreamHandler(f, fmtr)}, nil
}
75476
func (c *Client) messageHandler() {
	for {
		if c.scanner.Scan() {
			line := c.scanner.Text()
			if line == "error id=0 msg=ok" {
				c.err <- nil
			} else if matches := respTrailerRe.FindStringSubmatch(line); len(matches) == 4 {
				c.err <- NewError(matches)
			} else if strings.Index(line, "notify") == 0 {
				if n, err := decodeNotification(line); err == nil {
					// non-blocking write
					select {
					case c.notify <- n:
					default:
					}
				}
			} else {
				c.res = append(c.res, line)
			}
		} else {
			err := c.scanErr()
			c.err <- err
			if err == io.ErrUnexpectedEOF {
				close(c.disconnect)
				return
			}
		}
	}
}
95335
func MessageHandler(Incoming <-chan tgbot.MessageWithUpdateID, bot *tgbot.TgBot) {
	for {
		input := <-Incoming

		if input.Msg.Text != nil {
			text := handleMessageText(*input.Msg.Text, input.Msg)
			if text != "" {
				nmsg, err := bot.SimpleSendMessage(input.Msg, text)
				if err != nil {
					fmt.Println(err)
					continue
				}
				fmt.Println(nmsg.String())
			}
		}
	}
}
214608
func (c *Context) APIHandler(builder Builder) http.Handler {
	b := builder
	if b == nil {
		b = PassthroughBuilder
	}

	var title string
	sp := c.spec.Spec()
	if sp != nil && sp.Info != nil && sp.Info.Title != "" {
		title = sp.Info.Title
	}

	redocOpts := RedocOpts{
		BasePath: c.BasePath(),
		Title:    title,
	}

	return Spec("", c.spec.Raw(), Redoc(redocOpts, c.RoutesHandler(b)))
}
706144
func (r *Registry) HTTPHandler() http.Handler {
	opts := promhttp.HandlerOpts{
		ErrorLog: promLogger{r: r},
		// TODO(mr): decide if we want to set MaxRequestsInFlight or Timeout.
	}
	return promhttp.HandlerFor(r.Registry, opts)
}
500708
func NewHandler() http.Handler {
	return api.HTTPHandler{
		Handler: api.HandlerFunc(gencrlHandler),
		Methods: []string{"POST"},
	}
}
1364530
func SNIHandler(opts ...HandlerOption) Handler {
	h := &sniHandler{}
	h.Init(opts...)

	return h
}
1012155
func handleBytes(w http.ResponseWriter, r *http.Request, streaming bool) {
	parts := strings.Split(r.URL.Path, "/")
	if len(parts) != 3 {
		http.Error(w, "Not found", http.StatusNotFound)
		return
	}

	numBytes, err := strconv.Atoi(parts[2])
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	if numBytes < 1 {
		numBytes = 1
	} else if numBytes > 100*1024 {
		numBytes = 100 * 1024
	}

	var chunkSize int
	var write func([]byte)

	if streaming {
		if r.URL.Query().Get("chunk_size") != "" {
			chunkSize, err = strconv.Atoi(r.URL.Query().Get("chunk_size"))
			if err != nil {
				http.Error(w, err.Error(), http.StatusBadRequest)
				return
			}
		} else {
			chunkSize = 10 * 1024
		}

		write = func() func(chunk []byte) {
			f := w.(http.Flusher)
			return func(chunk []byte) {
				w.Write(chunk)
				f.Flush()
			}
		}()
	} else {
		chunkSize = numBytes
		write = func(chunk []byte) {
			w.Header().Set("Content-Length", strconv.Itoa(len(chunk)))
			w.Write(chunk)
		}
	}

	var seed int64
	rawSeed := r.URL.Query().Get("seed")
	if rawSeed != "" {
		seed, err = strconv.ParseInt(rawSeed, 10, 64)
		if err != nil {
			http.Error(w, "invalid seed", http.StatusBadRequest)
			return
		}
	} else {
		seed = time.Now().Unix()
	}

	src := rand.NewSource(seed)
	rng := rand.New(src)

	w.Header().Set("Content-Type", "application/octet-stream")
	w.WriteHeader(http.StatusOK)

	var chunk []byte
	for i := 0; i < numBytes; i++ {
		chunk = append(chunk, byte(rng.Intn(256)))
		if len(chunk) == chunkSize {
			write(chunk)
			chunk = nil
		}
	}
	if len(chunk) > 0 {
		write(chunk)
	}
}
710797
func (m *Mux) UseHandler(phase string, fn c.HandlerFunc) *Mux {
	m.Middleware.UseHandler(phase, fn)
	return m
}
77096
func NewUnaryHandler(params UnaryHandlerParams) transport.UnaryHandler {
	return newUnaryHandler(params.Handle, params.NewRequest)
}
437578
func bytesBinaryReader(ior io.Reader) ([]byte, error) {
	size, err := longBinaryReader(ior)
	if err != nil {
		return nil, fmt.Errorf("cannot read bytes: cannot read size: %s", err)
	}
	if size < 0 {
		return nil, fmt.Errorf("cannot read bytes: size is negative: %d", size)
	}
	if size > MaxBlockSize {
		return nil, fmt.Errorf("cannot read bytes: size exceeds MaxBlockSize: %d > %d", size, MaxBlockSize)
	}
	buf := make([]byte, size)
	_, err = io.ReadAtLeast(ior, buf, int(size))
	if err != nil {
		return nil, fmt.Errorf("cannot read bytes: %s", err)
	}
	return buf, nil
}
599194
func (s *storageRESTServer) ReadFileHandler(w http.ResponseWriter, r *http.Request) {
	if !s.IsValid(w, r) {
		return
	}
	vars := mux.Vars(r)
	volume := vars[storageRESTVolume]
	filePath := vars[storageRESTFilePath]
	offset, err := strconv.Atoi(vars[storageRESTOffset])
	if err != nil {
		s.writeErrorResponse(w, err)
		return
	}
	length, err := strconv.Atoi(vars[storageRESTLength])
	if err != nil {
		s.writeErrorResponse(w, err)
		return
	}
	if offset < 0 || length < 0 {
		s.writeErrorResponse(w, errInvalidArgument)
		return
	}
	var verifier *BitrotVerifier
	if vars[storageRESTBitrotAlgo] != "" {
		hashStr := vars[storageRESTBitrotHash]
		var hash []byte
		hash, err = hex.DecodeString(hashStr)
		if err != nil {
			s.writeErrorResponse(w, err)
			return
		}
		verifier = NewBitrotVerifier(BitrotAlgorithmFromString(vars[storageRESTBitrotAlgo]), hash)
	}
	buf := make([]byte, length)
	_, err = s.storage.ReadFile(volume, filePath, int64(offset), buf, verifier)
	if err != nil {
		s.writeErrorResponse(w, err)
		return
	}
	w.Header().Set("Content-Length", strconv.Itoa(len(buf)))
	w.Write(buf)
	w.(http.Flusher).Flush()
}
1247126
func (n *Node) RPCHandler() (*rpc.Server, error) {
	n.lock.RLock()
	defer n.lock.RUnlock()

	if n.inprocHandler == nil {
		return nil, ErrNodeStopped
	}
	return n.inprocHandler, nil
}