// Code inspired by
// https://github.com/jaegertracing/jaeger/blob/89f3ccaef21d256728f02ec9d73b31f9c3bde71a/cmd/collector/app/http_handler.go#L61
483671
func (decoder *JaegerThriftTraceDecoderV1) Read(ctx context.Context, req *http.Request) error {
	buf := decoder.bufferPool.Get().(*bytes.Buffer)
	defer decoder.bufferPool.Put(buf)
	buf.Reset()

	_, err := io.Copy(buf, req.Body)
	if err != nil {
		return errors.New("could not read request body")
	}

	protocol := decoder.protocolFactory.GetProtocol(&thrift.TMemoryBuffer{
		Buffer: buf,
	})
	batch := jThrift.Batch{}
	if err := batch.Read(protocol); err != nil {
		return errInvalidJaegerTraceFormat
	}

	spans := convertJaegerBatch(&batch)

	return decoder.Sink.AddSpans(ctx, spans)
}
957088
func AWSErrorCode(err error) string {
	if awsError, ok := err.(awserr.Error); ok {
		return awsError.Code()
	}
	return ""
}
657721
func (r *rest) AppAuthCode(c *gin.Context) {

	// build credentials
	var cc clientCredential
	cc.ClientId = c.Query("client_id")
	cc.ClientSecret = c.Query("client_secret")

	code := c.Query("code")

	if code == "" {
		c.JSON(http.StatusBadRequest, gin.H{"message": "no code was provided"})
		return
	}

	jr := make(map[string]interface{})

	// build access code url
	authURL := fmt.Sprintf(
		"%s/authentication/token?grant_type=authorization_code&client_id=%s&client_secret=%s&state=xyz&redirect_uri=%s&code=%s",
		config.GAppUrl,
		cc.ClientId,
		cc.ClientSecret,
		url.QueryEscape(
			fmt.Sprintf("%s/authentication/oauth2/code", config.GAppUrl),
		), url.QueryEscape(code),
	)

	// build app credentials
	auth := osin.BasicAuth{Username: cc.ClientId, Password: cc.ClientSecret}

	// if parse, download and parse json
	if c.Query("parse") == "yes" {
		if err := downloadAccessToken(authURL, &auth, jr); err != nil {
			c.JSON(apihelper.BuildRequestError(err))
			return
		}
	}

	// show json error
	if err, ok := jr["error"]; ok {
		c.JSON(apihelper.BuildRequestError(errors.New(err)))
		return
	}

	if _, ok := jr["access_token"]; ok {
		c.JSON(http.StatusOK, jr)
		return
	}

	cururl := *c.Request.URL
	curq := cururl.Query()
	curq.Add("parse", "yes")
	cururl.RawQuery = curq.Encode()
	c.JSON(http.StatusOK, gin.H{
		"state": c.Query("state"),
		"code":  c.Query("code"),
	})
}
664026
func S3ManagerUploadInputGoCode(a *API) string {
	if v := a.PackageName(); v != "s3" {
		panic(fmt.Sprintf("unexpected API model %s", v))
	}

	s, ok := a.Shapes["PutObjectInput"]
	if !ok {
		panic(fmt.Sprintf("unable to find PutObjectInput shape in S3 model"))
	}

	a.resetImports()
	a.imports["io"] = true
	a.imports["time"] = true

	var w bytes.Buffer
	if err := s3managerUploadInputTmpl.Execute(&w, s); err != nil {
		panic(fmt.Sprintf("failed to execute %s template, %v",
			s3managerUploadInputTmpl.Name(), err))
	}

	return a.importsGoCode() + w.String()
}
972002
func handleAuthorizationCode(c context.Context, cfg *Settings, code string) (uid string, u *auth.User, err error) {
	if cfg.ClientID == "" || cfg.ClientSecret == "" || cfg.RedirectURI == "" {
		return "", nil, ErrNotConfigured
	}

	// Validate the discover doc has necessary fields to proceed.
	discovery, err := fetchDiscoveryDoc(c, cfg.DiscoveryURL)
	switch {
	case err != nil:
		return "", nil, err
	case discovery.TokenEndpoint == "":
		return "", nil, errors.New("openid: bad discovery doc, empty token_endpoint")
	}

	// Prepare a request to exchange authorization code for the ID token.
	v := url.Values{}
	v.Set("code", code)
	v.Set("client_id", cfg.ClientID)
	v.Set("client_secret", cfg.ClientSecret)
	v.Set("redirect_uri", cfg.RedirectURI)
	v.Set("grant_type", "authorization_code")
	payload := v.Encode()

	// Send POST to the token endpoint with URL-encoded parameters to get back the
	// ID token. There's more stuff in the reply, we don't need it.
	var token struct {
		IDToken string `json:"id_token"`
	}
	req := internal.Request{
		Method: "POST",
		URL:    discovery.TokenEndpoint,
		Body:   []byte(payload),
		Headers: map[string]string{
			"Content-Type": "application/x-www-form-urlencoded",
		},
		Out: &token,
	}
	if err := req.Do(c); err != nil {
		return "", nil, err
	}

	// Unpack the ID token to grab the user information from it.
	return userFromIDToken(c, token.IDToken, cfg, discovery)
}
1047817
func LogResponseCode(span opentracing.Span, code int) {
	if span != nil {
		ext.HTTPStatusCode.Set(span, uint16(code))
		if code >= 400 {
			ext.Error.Set(span, true)
		}
	}
}
925034
func (oauth *Oauth) GetQyUserInfoByCode(code string) (result QyUserInfo, err error) {
	qyAccessToken, e := oauth.GetQyAccessToken()
	if e != nil {
		err = e
		return
	}
	urlStr := fmt.Sprintf(qyUserInfoURL, qyAccessToken, code)
	var response []byte
	response, err = util.HTTPGet(urlStr)
	if err != nil {
		return
	}
	err = json.Unmarshal(response, &result)
	if err != nil {
		return
	}
	if result.ErrCode != 0 {
		err = fmt.Errorf("GetQyUserInfoByCode error : errcode=%v , errmsg=%v", result.ErrCode, result.ErrMsg)
		return
	}
	return
}
408553
func main() {

	rpc := grpc.NewServer()
	pb.RegisterGreeterServer(rpc, &server{})

	app := gear.New()
	app.UseHandler(logging.Default())

	app.Use(func(ctx *gear.Context) error {
		// "application/grpc", "application/grpc+proto"
		if strings.HasPrefix(ctx.GetHeader(gear.HeaderContentType), "application/grpc") {
			rpc.ServeHTTP(ctx.Res, ctx.Req)
			ctx.End(204) // Must end with 204 to handle rpc error
		}
		return nil
	})
	app.Use(func(ctx *gear.Context) error {
		return ctx.HTML(200, "<h1>gRPC</h1>")
	})

	log.Fatalln(app.ListenTLS(":3000", "./testdata/out/test.crt", "./testdata/out/test.key"))
}
977371
func (h *JSONWriter) WriteCode(w http.ResponseWriter, r *http.Request, code int, e interface{}) {
	js, err := json.Marshal(e)
	if err != nil {
		h.WriteError(w, r, errors.WithStack(err))
		return
	}

	if code == 0 {
		code = http.StatusOK
	}

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(code)
	w.Write(js)
}
726431
func NewJaegerThriftTraceDecoderV1(logger log.Logger, sink trace.Sink) *JaegerThriftTraceDecoderV1 {
	return &JaegerThriftTraceDecoderV1{
		Logger:          logger,
		Sink:            sink,
		protocolFactory: thrift.NewTBinaryProtocolFactoryDefault(),
		bufferPool: sync.Pool{
			New: func() interface{} {
				return bytes.NewBuffer(make([]byte, 0, 2048))
			},
		},
	}

}
382552
func (client *Client) Handler(h http.Handler) http.Handler {
	if h == nil {
		h = http.DefaultServeMux
	}
	fn := func(w http.ResponseWriter, r *http.Request) {
		defer func() {
			if err := recover(); err != nil {
				client.Notify(newError(err, 2), Params(r.Form), getCGIData(r), *r.URL)
				panic(err)
			}
		}()
		h.ServeHTTP(w, r)
	}
	return http.HandlerFunc(fn)
}
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)))
}
414449
func Handler(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		rc := &responseCapture{w, 0}

		s := time.Now()
		h.ServeHTTP(rc, req)
		e := time.Now()
		d := e.Sub(s)

		data := Data{
			"start":    s,
			"end":      e,
			"duration": d,
			"status":   rc.statusCode,
			"method":   req.Method,
			"path":     req.URL.Path,
		}
		if len(req.URL.RawQuery) > 0 {
			data["query"] = req.URL.Query()
		}
		Event("request", GetRequestID(req), data)
	})
}
1194009
func (h *NegotiationHandler) WriteCode(w http.ResponseWriter, r *http.Request, code int, e interface{}) {
	switch httputil.NegotiateContentType(r, []string{}, "application/json") {
	case "text/html":
		h.html.WriteCode(w, r, code, e)
		return
	case "text/plain":
		h.plain.WriteCode(w, r, code, e)
		return
	case "application/json":
		h.json.WriteCode(w, r, code, e)
		return
	default:
		h.json.WriteCode(w, r, code, e)
		return
	}
}
727045
func Handler(zebedeeURL string) func(http.Handler) http.Handler {
	authClient := clientsidentity.NewAPIClient(nil, zebedeeURL)
	return HandlerForHTTPClient(authClient)
}
125758
func (a *API) ExampleGoCode() string {
	exs := []string{}
	imports := map[string]bool{}
	for _, o := range a.OperationList() {
		o.imports = map[string]bool{}
		exs = append(exs, o.Example())
		for k, v := range o.imports {
			imports[k] = v
		}
	}

	code := fmt.Sprintf("import (\n%q\n%q\n%q\n\n%q\n%q\n%q\n",
		"bytes",
		"fmt",
		"time",
		SDKImportRoot+"/aws",
		SDKImportRoot+"/aws/session",
		a.ImportPath(),
	)
	for k := range imports {
		code += fmt.Sprintf("%q\n", k)
	}
	code += ")\n\n"
	code += "var _ time.Duration\nvar _ bytes.Buffer\n\n"
	code += strings.Join(exs, "\n\n")
	return code
}
1301034
func MakeHandler(ts Service, logger kitlog.Logger) http.Handler {
	r := mux.NewRouter()

	opts := []kithttp.ServerOption{
		kithttp.ServerErrorHandler(kittransport.NewLogErrorHandler(logger)),
		kithttp.ServerErrorEncoder(encodeError),
	}

	trackCargoHandler := kithttp.NewServer(
		makeTrackCargoEndpoint(ts),
		decodeTrackCargoRequest,
		encodeResponse,
		opts...,
	)

	r.Handle("/tracking/v1/cargos/{id}", trackCargoHandler).Methods("GET")

	return r
}