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


Golang Context.MapTo方法代碼示例

本文整理匯總了Golang中github.com/go-martini/martini.Context.MapTo方法的典型用法代碼示例。如果您正苦於以下問題:Golang Context.MapTo方法的具體用法?Golang Context.MapTo怎麽用?Golang Context.MapTo使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在github.com/go-martini/martini.Context的用法示例。


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

示例1: MapEncoder

// MapEncoder intercepts the request's URL, detects the requested format,
// and injects the correct encoder dependency for this request. It rewrites
// the URL to remove the format extension, so that routes can be defined
// without it.
func MapEncoder(c martini.Context, w http.ResponseWriter, r *http.Request) {
	// Get the format extension
	matches := rxExt.FindStringSubmatch(r.URL.Path)
	ft := ".json"
	if len(matches) > 1 {
		// Rewrite the URL without the format extension
		l := len(r.URL.Path) - len(matches[1])
		if strings.HasSuffix(r.URL.Path, "/") {
			l--
		}
		r.URL.Path = r.URL.Path[:l]
		ft = matches[1]
	}

	log.Println(r.URL.Path)

	// Inject the requested encoder
	switch ft {
	case ".xml":
		//c.MapTo(&xmlEncoder{}, (*Encoder)(nil))
		w.Header().Set("Content-Type", "application/xml")
	case ".text":
		//c.MapTo(&textEncoder{}, (*Encoder)(nil))
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
	default:
		c.MapTo(&jsonEncoder{}, (*Encoder)(nil))
		w.Header().Set("Content-Type", "application/json")
	}
}
開發者ID:jcgarciam,項目名稱:go-wasab,代碼行數:33,代碼來源:encoder.go

示例2: validateAndMap

// Performs validation and combines errors from validation
// with errors from deserialization, then maps both the
// resulting struct and the errors to the context.
func validateAndMap(obj reflect.Value, context martini.Context, errors Errors, ifacePtr ...interface{}) {
	context.Invoke(Validate(obj.Interface()))
	errors = append(errors, getErrors(context)...)
	context.Map(errors)
	context.Map(obj.Elem().Interface())
	if len(ifacePtr) > 0 {
		context.MapTo(obj.Elem().Interface(), ifacePtr[0])
	}
}
開發者ID:joshrendek,項目名稱:pgdiagnose,代碼行數:12,代碼來源:binding.go

示例3: validateAndMap

// Performs validation and combines errors from validation
// with errors from deserialization, then maps both the
// resulting struct and the errors to the context.
func validateAndMap(obj reflect.Value, context martini.Context, errors *base.BindingErrors, ifacePtr ...interface{}) {
	context.Invoke(Validate(obj.Interface()))
	errors.Combine(getErrors(context))
	context.Map(*errors)
	context.Map(obj.Elem().Interface())
	if len(ifacePtr) > 0 {
		context.MapTo(obj.Elem().Interface(), ifacePtr[0])
	}
}
開發者ID:Julianzz,項目名稱:gogs,代碼行數:12,代碼來源:binding.go

示例4: ContentMiddleware

// ContentMiddleware is a Martini handler which specifies the proper
// serialization (XML/JSON) depending on the "Content-Type" header
// presented.
func ContentMiddleware(c martini.Context, w http.ResponseWriter, r *http.Request) {
	switch r.Header.Get("Content-Type") {
	case "application/xml":
		c.MapTo(encoder.XmlEncoder{}, (*encoder.Encoder)(nil))
		w.Header().Set("Content-Type", "application/xml; charset=utf-8")
	default:
		c.MapTo(encoder.JsonEncoder{}, (*encoder.Encoder)(nil))
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
	}
}
開發者ID:jbuchbinder,項目名稱:martiniframework,代碼行數:13,代碼來源:middleware.go

示例5: Document

func Document(c martini.Context, w http.ResponseWriter, r *http.Request) {
	if !yaag.IsOn() {
		c.Next()
		return
	}
	apiCall := models.ApiCall{}
	writer := httptest.NewRecorder()
	c.MapTo(writer, (*http.ResponseWriter)(nil))
	middleware.Before(&apiCall, r)
	c.Next()
	middleware.After(&apiCall, writer, w, r)
}
開發者ID:kiyor,項目名稱:yaag,代碼行數:12,代碼來源:middleware.go

示例6: AppengineContextProvider

func AppengineContextProvider(c martini.Context, request *http.Request) {
	gae := appengine.NewContext(request)
	namespace := appengine.ModuleName(gae)

	context, err := appengine.Namespace(gae, namespace)

	if err != nil {
		panic(fmt.Sprintf("Could not create GAE context: %v", err))
	}

	c.MapTo(context, (*appengine.Context)(nil))
}
開發者ID:BearchInc,項目名稱:fala-com-meu-carro,代碼行數:12,代碼來源:appengine_context_provider.go

示例7: validateAndMap

// Performs validation and combines errors from validation
// with errors from deserialization, then maps both the
// resulting struct and the errors to the context.
func validateAndMap(val reflect.Value, context martini.Context, errors *Errors, ifacePtr ...interface{}) {
	context.Invoke(Validate(val.Interface()))
	context.Map(errors)
	target, _ := normalize(val, context)
	if target == nil {
		panic("binding: wrong return nil value")
	}
	context.Map(target)
	if len(ifacePtr) > 0 {
		for index, _ := range ifacePtr {
			context.MapTo(target, ifacePtr[index])
		}
	}
}
開發者ID:jenchik,項目名稱:binding,代碼行數:17,代碼來源:binding.go

示例8: MapEncoder

func MapEncoder(c martini.Context, w http.ResponseWriter, r *http.Request) {
	accept := r.Header.Get("Accept")
	if accept == "*/*" {
		accept = r.Header.Get("Content-Type")
	}
	matches := rxAccept.FindStringSubmatch(accept)

	dt := "json"
	if len(matches) == 1 {
		dt = matches[0]
	}
	switch dt {
	case "xml":

		c.MapTo(XmlEncoder{}, (*Encoder)(nil))
		w.Header().Set("Content-Type", "application/xml")
	case "plain":
		c.MapTo(TextEncoder{}, (*Encoder)(nil))
		w.Header().Set("Content-Type", "text/plain")
	case "html":
		c.MapTo(TextEncoder{}, (*Encoder)(nil))
		w.Header().Set("Content-Type", "text/html")
	default:
		c.MapTo(JsonEncoder{}, (*Encoder)(nil))
		w.Header().Set("Content-Type", "application/json")
	}
}
開發者ID:ninnemana,項目名稱:API,代碼行數:27,代碼來源:encoding.go

示例9: LoginRequired

func LoginRequired(db d.DB, c martini.Context, r render.Render, req *http.Request) {
	user, err := GetCurrentUser(req, db)
	if err != nil {
		log.Printf("AUTH can not retrieve user %v", err)
		path := fmt.Sprintf("%s?%s=%s", AUTH_URL, REDIRECT_PARAM, req.URL.Path)
		r.Redirect(path, 302)
		return
	}
	if user != nil && user.IsAuthenticated() {
		c.MapTo(user, (*User)(nil))
		return
	}
	log.Printf("user not authentificated or not found :( ")
	path := fmt.Sprintf("%s?%s=%s", AUTH_URL, REDIRECT_PARAM, req.URL.Path)
	r.Redirect(path, 302)
}
開發者ID:AlexeyProskuryakov,項目名稱:kukuau_api_bot,代碼行數:16,代碼來源:Users.go

示例10: MapCodec

func MapCodec(c martini.Context, r *http.Request) {
	if r.Method == "POST" || r.Method == "PUT" {
		c_type := r.Header["Content-Type"]
		if len(c_type) != 1 {
			panic("That's unreasonable")
		}
		encoder := map[string]Decoder{
			"application/json": jsonDecoder{},
		}[c_type[0]]

		if encoder == nil {
		}
	} else {
		c.MapTo(jsonEncoder{}, (*Encoder)(nil))
	}
}
開發者ID:riannucci,項目名稱:fish_basket,代碼行數:16,代碼來源:routes.go

示例11: UserInject

func UserInject(session sessions.Session, ctx martini.Context) {
	u := user{isLoggedIn: false, username: "", id: "", github: nil}

	if session.Get("loggedin") != nil {
		u.isLoggedIn = true
		u.username = session.Get("username").(string)
		u.id = session.Get("id").(string)

		ts := oauth2.StaticTokenSource(
			&oauth2.Token{AccessToken: session.Get("token").(string)},
		)

		tc := oauth2.NewClient(oauth2.NoContext, ts)
		client := github.NewClient(tc)

		u.github = client
	}

	ctx.MapTo(u, (*User)(nil))
}
開發者ID:SemQuery,項目名稱:web,代碼行數:20,代碼來源:user.go

示例12: MapEncoder

// MapEncoder intercepts the request's URL, detects the requested format,
// and injects the correct encoder dependency for this request. It rewrites
// the URL to remove the format extension, so that routes can be defined
// without it.
func MapEncoder(c martini.Context, w http.ResponseWriter, r *http.Request) {

	reg, err := regexp.Compile("[^A-Za-z0-9]+")
	if err != nil {
		panic(err)
	}
	prettyurl := reg.ReplaceAllString(r.URL.Path, "-")
	re := regexp.MustCompile(":([^/]*)")
	prettyurl = re.ReplaceAllString(prettyurl, "{$1}")

	// Get the format extension
	matches := rxExt.FindStringSubmatch(prettyurl)
	ft := ".json"
	if len(matches) > 1 {
		// Rewrite the URL without the format extension
		l := len(r.URL.Path) - len(matches[1])
		if strings.HasSuffix(r.URL.Path, "/") {
			l--
		}
		r.URL.Path = r.URL.Path[:l]
		ft = matches[1]
	}
	// Inject the requested encoder
	switch ft {
	case ".xml":
		c.MapTo(xmlEncoder{}, (*Encoder)(nil))
		w.Header().Set("Content-Type", "application/xml")
	case ".text":
		c.MapTo(textEncoder{}, (*Encoder)(nil))
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
	default:
		c.MapTo(jsonEncoder{}, (*Encoder)(nil))
		w.Header().Set("Content-Type", "application/json")
	}
}
開發者ID:haruio,項目名稱:haru-golang-helpcenter,代碼行數:39,代碼來源:encoding.go

示例13: MapEncoder

func MapEncoder(c martini.Context, w http.ResponseWriter, r *http.Request) {
	// Get the format extension
	matches := rxExt.FindStringSubmatch(r.URL.Path)
	ext := ".json"
	if len(matches) > 1 {
		// Rewrite the URL without the format extension
		lentghWithoutExt := len(r.URL.Path) - len(matches[1])
		if strings.HasSuffix(r.URL.Path, "/") {
			lentghWithoutExt--
		}
		r.URL.Path = r.URL.Path[:lentghWithoutExt]
		ext = matches[1]
	}
	// Inject the requested encoder
	switch ext {
	case ".xml":
		c.MapTo(encoder.XmlEncoder{}, (*encoder.Encoder)(nil))
		w.Header().Set("Content-Type", "application/xml")
	default:
		c.MapTo(encoder.JsonEncoder{}, (*encoder.Encoder)(nil))
		w.Header().Set("Content-Type", "application/json")
	}
}
開發者ID:yc850k,項目名稱:haha,代碼行數:23,代碼來源:server.go

示例14: Authentication

// Middleware for Martini which tries to identify the request user by the Authorization header.
// If no such header exists, it checks the session cookie.  If that also fails, it assumes the user is a guest.
// If the header exists but can't be decoded, it returns a 401 status.
// It uses Martini's dependency injection system to register the user for later consumption.
func Authentication(c martini.Context, req *http.Request, res http.ResponseWriter, session sessions.Session) {
	// Get the Authorization header
	a := req.Header.Get("Authorization")
	if a == "" {
		// No header - Check for a session
		u := session.Get("user")
		if u == nil {
			// No session either, set the user as a guest
			c.MapTo(ANON_USER, (*User)(nil))
		} else {
			// Register the user from the session
			c.MapTo(u, (*User)(nil))
		}
		return
	}

	// Remove the 'Basic ' prefix
	a = strings.TrimPrefix(a, "Basic ")

	// Decode the Authorization header
	data, err := base64.StdEncoding.DecodeString(a)
	if err != nil {
		// Bad Authorization value - return 401 Unauthorized
		http.Error(res, "Could not decode Authorization header", http.StatusUnauthorized)
		// Note: If the response gets written to, Martini doesn't call any subsequent handlers
		return
	}

	// Split out the username and password
	s := strings.Split(string(data), ":")
	if len(s) < 2 {
		// Bad Authorization value - return 401 Unauthorized
		http.Error(res, "Authorization header requires a username and password", http.StatusUnauthorized)
		// Note: If the response gets written to, Martini doesn't call any subsequent handlers
		return
	}

	// At this point, you would normally lookup a user database
	// Since this is an example - we're just accepting the username as is
	c.MapTo(s[0], (*User)(nil))

	// Set the user in the session
	session.Set("user", s[0])
}
開發者ID:rolaveric,項目名稱:GoHttp,代碼行數:48,代碼來源:main.go

示例15: MapEncoder

func MapEncoder(c martini.Context, w http.ResponseWriter, r *http.Request) {
	c.MapTo(jsonEncoder{}, (*Encoder)(nil))
	w.Header().Set("Content-Type", "application/json")
}
開發者ID:kidoman,項目名稱:server-browser,代碼行數:4,代碼來源:encoding.go


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