Пример #1
0
// Reverse would reverse the named routes with params supported. E.g. we have a routes "/hello/:name" named "Hello",
// then we can call s.Reverse("Hello", "world") gives us "/hello/world"
func (s *Server) Reverse(name string, params ...interface{}) string {
	path, ok := s.namedRoutes[name]
	if !ok {
		log.Warnf("Server routes reverse failed, cannot find named routes %q", name)
		return "/no_such_named_routes_defined"
	}
	if len(params) == 0 || path == "/" {
		return path
	}
	strParams := make([]string, len(params))
	for i, param := range params {
		strParams[i] = fmt.Sprint(param)
	}
	parts := strings.Split(path, "/")[1:]
	paramIndex := 0
	for i, part := range parts {
		if part[0] == ':' || part[0] == '*' {
			if paramIndex < len(strParams) {
				parts[i] = strParams[paramIndex]
				paramIndex++
			}
		}
	}
	return httprouter.CleanPath("/" + strings.Join(parts, "/"))
}
Пример #2
0
func (q *Queue) DequeueJson(value interface{}, startId ...uint64) (uint64, error) {
	id, data, err := q.Dequeue(startId...)
	if err != nil {
		return id, err
	}
	if err := json.Unmarshal(data, value); err != nil {
		log.Warnf("[Queue] Error when decoding json, %s", err)
		return id, err
	}
	return id, nil
}
Пример #3
0
func (q *Queue) EnqueueGob(value interface{}) (uint64, error) {
	buf := q.bufPool.Get()
	defer func() {
		buf.Reset()
		q.bufPool.Put(buf)
	}()

	enc := gob.NewEncoder(buf)
	if err := enc.Encode(value); err != nil {
		log.Warnf("[Queue] Error when encoding object into gob, %s", err)
		return 0, err
	}
	return q.Enqueue(buf.Bytes())
}
Пример #4
0
func (q *Queue) DequeueGob(value interface{}, startId ...uint64) (uint64, error) {
	id, data, err := q.Dequeue(startId...)
	if err != nil {
		return id, err
	}

	buf := q.bufPool.Get()
	defer func() {
		buf.Reset()
		q.bufPool.Put(buf)
	}()
	buf.Write(data)
	dec := gob.NewDecoder(buf)
	if err := dec.Decode(value); err != nil {
		log.Warnf("[Queue] Error when decoding gob, %s", err)
		return id, err
	}
	return id, nil
}
Пример #5
0
// ServeHTTP implements the Middleware interface. Would log all the access, status and performance information.
func (m *StatWare) ServeHTTP(ctx context.Context, w http.ResponseWriter, r *http.Request, next Handler) context.Context {
	start := time.Now()
	newCtx := next(ctx, w, r)
	res := w.(ResponseWriter)
	urlPath := r.URL.Path
	if res.Status() >= 400 {
		log.Warnf("Request %q %q, status=%v, size=%d, duration=%v",
			r.Method, r.URL.Path, res.Status(), res.Size(), time.Since(start))
	} else {
		ignored := false
		for _, prefix := range m.ignoredPrefixes {
			if strings.HasPrefix(urlPath, prefix) {
				ignored = true
				break
			}
		}
		if !ignored {
			log.Infof("Request %q %q, status=%v, size=%d, duration=%v",
				r.Method, r.URL.Path, res.Status(), res.Size(), time.Since(start))
		}
	}
	return newCtx
}