Пример #1
0
func processHeadersMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		optionsHeader := c.Request.Header.Get(CONTEXT_HEADER_OPTIONS)
		if optionsHeader == "" {
			optionsHeader = "{}"
		}

		var options models.Options
		options.FromString(optionsHeader)

		if options.Notify == nil {
			notify := true
			options.Notify = &notify
		}

		if options.Filter == nil {
			options.Filter = models.JSON{}
		}

		if options.Origin == "" {
			options.Origin = messaging.ORIGIN_API
		}

		log.Info("Request options:", optionsHeader)

		c.Set(CONTEXT_HEADER_OPTIONS, options)
		c.Next()
	}
}
Пример #2
0
func (c *ApiClient) SendRequest(url, method string, body interface{}, isArray bool) (interface{}, error) {
	log.Info(
		"Sending request",
		"BaseUrl:", c.BaseUrl,
		"Url:", url,
		"Method:", method,
		"Body:", body,
		"Token:", c.Token,
		"AppId:", c.AppId,
		"NotifyRealtime", c.NotifyRealTime,
	)

	var bodyStr = ""
	if body != nil {
		b, err := json.Marshal(body)
		if err != nil {
			log.Error(err)
			return nil, err
		}

		bodyStr = string(b)
	}

	req, err := http.NewRequest(method, c.BaseUrl+url, strings.NewReader(bodyStr))
	if err != nil {
		log.Error(err)
		return nil, err
	}

	opts := models.Options{}

	//todo: in app and not in app token
	if c.Token != "" {
		req.Header.Set("Authorization", "Bearer "+c.Token)
	}

	if c.ClientId != "" {
		opts.ClientId = &c.ClientId
	}

	opts.Notify = &c.NotifyRealTime
	opts.Filter = c.Filter
	//opts.Origin = c.Origin

	optsS, err := opts.String()
	if err != nil {
		log.Error(err)
		return nil, err
	}

	req.Header.Set("NeutrinoOptions", optsS)

	client := http.Client{}
	res, err := client.Do(req)
	if err != nil {
		log.Info(err)
		return nil, err
	}

	if res == nil {
		log.Error("Unknown error")
		return nil, nil
	}

	if res.StatusCode != http.StatusOK {
		log.Info(res, err)
		return nil, err
	}

	defer res.Body.Close()
	if err != nil {
		log.Error(err)
		return nil, err
	}

	bodyRes, err := ioutil.ReadAll(res.Body)
	if err != nil {
		log.Error(err)
		return nil, err
	}

	if string(bodyRes) == "" {
		log.Info("Empty body response!")
		return nil, nil
	}

	var result interface{}
	log.Info("API response: ", string(bodyRes))
	if isArray {
		jsonArray := make([]models.JSON, 0)
		err = json.Unmarshal(bodyRes, &jsonArray)
		result = jsonArray
	} else {
		m := models.JSON{}
		err = json.Unmarshal(bodyRes, &m)
		result = m
	}

	if err != nil {
		log.Error(err)
		return nil, err
	}

	return result, nil
}