From Rails to KrakenD proxy: config generation for your routes

require "action_dispatch/routing/inspector"

begin
  namespace :krakend do
    task :routes => :environment do

      inspector = ActionDispatch::Routing::RoutesInspector.new(Rails.application.routes.routes)
      formatter = CustomRoutesFormatter.new
      routes_filter = {}

      puts inspector.format(formatter, routes_filter)
    end
  end
end

class CustomRoutesFormatter < ActionDispatch::Routing::ConsoleFormatter::Expanded
  def section_title(title)
  end

  def section(routes)
    @buffer << draw_expanded_section(routes)
  end

  private

  def draw_expanded_section(routes)
    routes.map.each_with_index do |r, i|
      path = r[:path].gsub("(.:format)", "").gsub(/:([a-z_]*)/, "{\\1}")

      <<~MESSAGE.chomp
        {
          "endpoint": "#{path}",
          "method": "#{r[:verb]}",
          "querystring_params": ["*"],
          "extra_config": {},
          "output_encoding": "no-op",
          "concurrent_calls": 1,
          "headers_to_pass": ["*"],
          "backend": [
            {
              "url_pattern": "#{path}",
              "encoding": "no-op",
              "extra_config": {},
              "sd": "static",
              "host": [
                "http://rails-app"
              ],
              "disable_host_sanitize": true
            }
          ]
        },
      MESSAGE
    end
  end
end

This approach can help you easily build krakend.json for your rails application.

Побывали на гвоздях

По счастливому стечению обстоятельств мы с Альбиной попали на замечательный тренинг Александра(https://vipassana.online).

На нем удалось получить очень ценные знания и научиться полезным практикам, естественно не обошлось без гвоздей, причем гвозди начались со входа – заходя в зал мы прошлись по дорожке из гвоздей.

Естественно гвозди торчали из досок под углом 90 градусов, а не были разбросаны на полу 🙂

На фото ниже виден результат стояния на гвоздях и медитации на гвоздях, ну и сами гвозди конечно же.

Для меня стало открытием как меняется восприятие и отношение к мыслям, зародился этот процесс на тренинге. но пришло это только утром следующего дня и возможно потребуется еще время для более глубокого осознания всего этого 🙂

Ну а теперь остается копить на четырехдневный тренинг и покупать гвозди для постоянных практик и очищения мозга.

GopherCon 2019

Побывали на Российской ГоферКонфе 🙂

Было очень полезно и интересно, очень понравились доклады от Konrad Reiche(go generate: One File to Rule Them All) и Денис Исаев(Линтеры в Go: как их готовить).

http://gophercon-russia.ru

Golang Hints: Create MongoDB Object ID from String

Sometimes you may want to find something by the Object ID in your MongoDB and due to you URI or query string contains ID you should convert the string ID to Object ID.

Below is a code that converts string ID to Object ID:

 package main

import (
"go.mongodb.org/mongo-driver/bson/primitive"
"fmt"
)
func main() {
oid, err := primitive.ObjectIDFromHex(recordID)

fmt.Printf("%s %v", err, oid)

  // if err := collection.FindOne(ctx, bson.M{"_id": oid}).Decode(e); err != nil {
  // return nil, err
// }
}

Presenting Go-Up

Today I have started development of new package for Golang-developers – Go-Up. I made it because I have noticed that I should repeat some things with each new project on Golang, so the main purpose of Go-Up package is to simplify building of new Golang applications.

This is a beginning so I just want to share link to GitHub here – https://github.com/ildarusmanov/go-up

401 with devise token based auth

Recently I had a problem with token based authentication, when we switched in our cluster for two pods for our rails-based application we had a 401 response for each second request.

So the problem was fixed with defining a secret key in devise config, it was very simple fix, but I spent a lot of time for looking a solution :(, because I thought that the problem is caused by sessions or some session data.

Why the problem have appeared?

Secret key in devise is used for generating your application token string and second part of token – body. So when you have two instances of the same application without defining your secret key you will have different results on checking your token.

You may check this by trying this line in your application console with different secret key.

KrakenD config example

What is KrakenD?

KrakenD is your self-designed REST API Gateway that feeds from your existing data services (Your APIs, legacy, cloud, IoT…) Just define visually or in a configuration file the endpoints your applications will use and the KrakenD will fetch and transform the content at your will for you.

https://www.krakend.io

Configuration example(proxy for POST, GET requests):

{
  "version": 2,
  "extra_config": {
    "github_com/devopsfaith/krakend-gologging": {
      "level": "WARNING",
      "prefix": "[KRAKEND]",
      "syslog": false,
      "stdout": true
    },
    "github_com/devopsfaith/krakend-metrics": {
      "collection_time": "60s",
      "proxy_disabled": false,
      "router_disabled": false,
      "backend_disabled": false,
      "endpoint_disabled": false,
      "listen_address": ":8090"
    },
    "github_com/devopsfaith/krakend-cors": {
      "allow_origins": [ "*" ],
      "allow_methods": [ "POST", "GET", "PUT", "DELETE" ],
      "allow_headers": [
        "Origin",
        "Authorization",
        "Content-Type",
        "Accept",
        "X-Auth-Token"
      ],
      "expose_headers": [ "Content-Length" ],
      "max_age": "12h"
    }
  },
  "timeout": "3000ms",
  "cache_ttl": "300s",
  "output_encoding": "no-op",
  "name": "api-proxy",
  "port": 80,
  "endpoints": [
    {
      "endpoint": "/",
      "extra_config": {},
      "output_encoding": "no-op",
      "concurrent_calls": 1,
      "backend": [
        {
          "url_pattern": "/",
          "encoding": "no-op",
          "extra_config": {},
          "sd": "static",
          "host": [
            "http://some-landing"
          ],
          "disable_host_sanitize": false
        }
      ]
    },
    {
      "method": "GET",
      "endpoint": "/api/v1/endpoint}",
      "extra_config": {},
      "output_encoding": "no-op",
      "concurrent_calls": 1,
      "backend": [
        {
          "method": "POST",
          "url_pattern": "/api/v1/{endpoint}",
          "encoding": "no-op",
          "extra_config": {},
          "sd": "static",
          "host": [
            "http://backend-service-getter"
          ],
          "disable_host_sanitize": false
        }
      ]
    },
    {
      "method": "POST",
      "endpoint": "/api/v1/endpoint}",
      "extra_config": {},
      "output_encoding": "no-op",
      "concurrent_calls": 1,
      "backend": [
        {
          "method": "POST",
          "url_pattern": "/api/v1/{endpoint}",
          "encoding": "no-op",
          "extra_config": {},
          "sd": "static",
          "host": [
            "http://backend-service-poster"
          ],
          "disable_host_sanitize": false
        }
      ]
    },
}

go build failed with “errors.go:121:2: undefined: stack”

Problem that I have met today:

$ go build
# github.com/pkg/errors
../../../../pkg/mod/github.com/pkg/errors@v0.8.0/errors.go:121:2: undefined: stack

#How to solve

I don't know the source of the problem, but I have fixed it with upgrading errors package version in my go.mod file:

module github.com/project_package
require (
// ...
github.com/pkg/errors v0.8.1 // indirect
// ...
)