<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by David Rieger on Medium]]></title>
        <description><![CDATA[Stories by David Rieger on Medium]]></description>
        <link>https://medium.com/@frontside?source=rss-11675b713da9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*nZHpI15s13hrHTvY.</url>
            <title>Stories by David Rieger on Medium</title>
            <link>https://medium.com/@frontside?source=rss-11675b713da9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 10:16:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@frontside/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[WebSockets in ~50 Lines of Go]]></title>
            <link>https://medium.com/hackernoon/websockets-in-50-lines-of-go-790214b9ed92?source=rss-11675b713da9------2</link>
            <guid isPermaLink="false">https://medium.com/p/790214b9ed92</guid>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[David Rieger]]></dc:creator>
            <pubDate>Mon, 24 May 2021 08:03:42 GMT</pubDate>
            <atom:updated>2021-05-24T08:17:29.445Z</atom:updated>
            <content:encoded><![CDATA[<p>If you are building an application that requires real-time transaction of data from server to client or bi-directional message transfers (such as Chat, Games, and certain types Notifications, etc.) you want to look at websockets.</p><p>Below I’m giving you — and guiding you through — the bare minimum of Go code required to build such a websocket.</p><p>At the end of this we will have two go applications that can be run independently from each other and will output following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_RN_8SPjziqaq5FLzSDQjg.png" /><figcaption>Simple websocket demo output. Left: client Right: server</figcaption></figure><h4>Disclaimer</h4><p>In an effort to keep it easy to read and highlight the parts actually directly required for websockets, I removed boiler plate code such as error handling. So beware that the below is not <em>good — </em>let alone <em>clean — </em>software.</p><h4>Prerequisites</h4><ul><li>Go installed on your computer (I’m using go1.14 in my example) and a basic understanding on how to write and execute go code.</li><li>The <a href="https://github.com/gorilla/websocket">Gorilla Websockets</a> go package</li></ul><h4>The Basics</h4><p>There are millions of tutorials and explanations on what a <a href="https://en.wikipedia.org/wiki/WebSocket">websocket </a>exactly is. For all intents and purposes (and because I don’t have a much better explanation) we can think of a websocket as an <em>elevated </em>HTTP connection.</p><p>So to get to a websocket, we first establish a normal HTTP connection and then <em>upgrade </em>it (and it really is called <a href="https://en.wikipedia.org/wiki/HTTP/1.1_Upgrade_header"><em>upgrading</em></a>). This will provide us with a websocket connection that we can hold on to and simple read to and write from (kind of like a go channel).</p><h4>The Server</h4><p>Below is the full code of a very basic server we can connect to and talk to via a websocket.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c6e33457c7285487abaa886b8725ce1/href">https://medium.com/media/0c6e33457c7285487abaa886b8725ce1/href</a></iframe><p>If we read through it (in order of execution) it will:</p><p>Line 59–63Start an HTTP server on localhost:8080 with an endpoint /ws.</p><p>Once an HTTP request is received on /ws:</p><p>L39Upgrade the HTTP connection to a websocket. This will return the actual connection type we need to hold on to for communicating.</p><p>L43, 15–24Start a consumer <em>go routine</em> which will read incoming messages from the socket and print it to the console.</p><p>L47, 50–57Send a couple of messages to the client by writing to the same socket connection.</p><p>And that’s all for the server.</p><h4>The Client</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4cc4c5cb2cfde46e20d4d77f4904e2a/href">https://medium.com/media/b4cc4c5cb2cfde46e20d4d77f4904e2a/href</a></iframe><p>Again reading through the code in order of execution, the client will:</p><p>L46, 10–15 Call the /ws endpoint on the server with a specific websocket dialer. This will return the connection object we need to hold on to for communicating.</p><p>L48, 17–28Start a consumer <em>go routine</em> which will read incoming messages from the socket and print it to the console (the exact same as on the server).</p><p>L50, 35–42Send a couple of messages to the client by writing to the same socket connection. Also the same as on the server, except with different messages</p><p>And that’s all for the client.</p><p>To run the programs, simply start the server first $ go run ./server and then the client in a separate terminal$ go run ./client.</p><p>By the way, the <em>sleeps </em>in both sendSomeMessages functions are entirely arbitrary and just here so you can follow the back and forth between server and client when you run the demo.</p><h4>A final Note</h4><p>The sending and receiving of messages between server and client happens entirely independent of each other. It’s not the usual <em>request-response </em>dynamic you get from HTTP connections. The server doesn’t <em>respond </em>to anything the client says, it just sends messages at will<em>. </em>A bit like UDP; but <strong>websockets do run on TCP</strong> and provide you with a transmission reliability that UDP doesn’t offer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=790214b9ed92" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/websockets-in-50-lines-of-go-790214b9ed92">WebSockets in ~50 Lines of Go</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn Go reflections and generic designs with a practical example]]></title>
            <link>https://medium.com/free-code-camp/a-practical-example-go-reflections-and-generic-designs-4868b6cdb2dc?source=rss-11675b713da9------2</link>
            <guid isPermaLink="false">https://medium.com/p/4868b6cdb2dc</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[David Rieger]]></dc:creator>
            <pubDate>Tue, 13 Mar 2018 19:13:41 GMT</pubDate>
            <atom:updated>2018-03-14T10:41:56.250Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0h2LEnphKQYkfi1INKpNWg.jpeg" /></figure><p>Reflections allow us to inspect and modify a program’s structure at its own runtime. In this article we will be looking at some parts of the go reflect package API and applying them to a real-world use case by building a <em>generic application configuration mechanism</em>.</p><h3>What we have and what we want</h3><p>We have implemented a Go <strong>data analysis application which will take data from an inventory database of a bookshop, process it, and turn it into human-readable statistical models</strong> that reflect the status of our inventory.</p><p>The output could, for example, be a list of books that were published by a certain author, or a bar chart depicting the number of books in our inventory per decade of publishing.</p><p><strong>What we want is a way for us to configure what the application generates from the raw data in an abstract manner.</strong> There might be hundreds of algorithms that all process the raw data in different ways and produce different outputs, but not all outputs are relevant to us every time we run the application. We want to be able to configure our application to suit our needs and then just let it do what it has to do in order to deliver what we want from it.</p><p>We also want to be able to let the analytical process <strong>run — with a fixed configuration — autonomously and periodically on a job scheduler</strong> (e.g. Jenkins, Rundeck or cron) and report to us the output we are interested in, without having to interact with it before each run.</p><p>Eventually, we want the application to be <strong>easily extensible</strong> so that we can add new algorithms with as little effort as possible and without breaking any workflows.</p><p><strong>Our core requirements on the architecture, therefore, are, in short:</strong></p><ul><li>Persistent and abstracted configuration</li><li>An interface through which both human users as well as other software (the job scheduler) can run the application</li><li>Intuitive extensibility</li></ul><h4>Approach 1: The complacent</h4><p>The most straightforward way to implement this is by first loading the raw data into our program, calling every analytical algorithm we want to run against it from the application’s main function, and eventually putting it all together in one nice report.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*2ThwL_28rJenWjCefiQv8g.png" /><figcaption>Self-contained application. The client and the business logic are the same piece of software.</figcaption></figure><pre>package main</pre><pre>func main() {<br>    rawData := Parse(&quot;books_db.flatfile&quot;)</pre><pre>// Run algorithms of our choice against the data<br>    bpDChart := amountOfBooksPerDecade(rawData)<br>    bpAList := booksPerAuthor(rawData)</pre><pre>createReport(bpDChart, bpAList)<br>}</pre><p>In terms of intuitive extensibility, this is probably as good as it gets (intuitive doesn’t imply good). Whenever we want to add a new analytical algorithm, we just implement it and call it in the main function if we want to run it.</p><p>However, there’s an obvious drawback: We need to touch the core application code and recompile the application not only whenever we extend the business logic, but also each time we want to change what is being generated by it (that is, each time we want to reconfigure it).</p><p>This approach doesn’t provide any sort of interface for the user to configure the application. It also <strong>doesn’t really address our requirement in an abstract manner to define what the application does</strong>. The developer of the software is basically the only one who can configure its behavior.</p><p>Of course, we could add a configuration file to the mix. This would allow us to select what algorithms to execute and which ones to omit without having to touch or recompile the application code. However, it will require some logic that maps the entries in the configuration file to (potentially hundreds of) functions in my application.</p><p>This logic will need to be adjusted each time I extend the application by a new analytical algorithm. Eventually, we will probably end up with a bunch of if statements running or omitting algorithms based on the presence or absence of strings in the configuration file. More on this later.</p><h4>Approach 2: The client-friendly</h4><p>The most common and perhaps cleanest way would be to provide a nice interface — a published API — on top of the analysis software, and a separate client, which talks to this API. The client can then decide whichever output it is interested in and call the appropriate API endpoints with according parameters. On the server side — our original analytics software — we then just run the relevant algorithms against the raw data, produce a report, and send it back to the client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*NeHD8rsa_rlPxT3ZvAQ-oA.png" /><figcaption>A clean architecture with a client talking to a published API on top of the business logic. Often a great approach, but it doesn’t come for free.</figcaption></figure><p>This probably makes for the cleanest architecture, but there are cases when it just isn’t the most ideal.</p><p>Looking at the requirements above and the previous approach, creating a separate client just moves the original problem from one place to another. Say I want to run the analytics application periodically with a certain setup (that is, with a certain definition of what output I’m interested in) and without having to interact with the application or its client each time it is run. I will need some sort of persistent configuration that maps to functions in my application. Whether I do that directly on the backend or on the client side doesn’t really matter to me.</p><p>Additionally, the extra interface and the client introduce a lot of inertia in terms of extensibility. Whenever we add a new analytical algorithm, which produces a different kind of statistical model, we need to adapt the interface of the service as well as the client which talks to this interface. Depending on who the client is, this might be well worth the effort, but in our case, it could just be unjustifiable overhead.</p><p>If my client was a human user who wants to press a couple of buttons to receive certain results at certain times, then yes, having a clean API exposing my analytics software is a must. But in this case, where the client is some job scheduler which we only touch every now and then, something else might be more suitable.</p><h4>Approach 3: The generic</h4><p>In order to address our requirements, we need to do two things: provide a design that doesn’t require us to maintain separate application layers (such as a segregated interface and a client) when extending the business logic, while at the same time allowing the client to define behavior without having to touch the application’s source code.</p><p>The first approach plus a configuration file would provide such a design. Writing a simple configuration file, parsing it, and then finding the appropriate algorithms to run is obvious enough. However, it doesn’t address extensibility very well.</p><p>Extending the business logic by adding new analytical algorithms will also require us to map parameters from the configuration file to the new algorithms. It will be necessary to adapt the config reader in order to support the new functionality. So we still have this extra layer that makes our software harder to extend.</p><p>It would be great if we could map parameters from the configuration file to functions in our business logic without having to explicitly implement a one to one (config to code) mapping for each of our (potentially hundreds of) analytical algorithms. Reflections enter the room.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*nY3XI__S6O5PXrjdLIsJyQ.png" /><figcaption>Drawing of Gopher by Renee French (reneefrench.blogspot.com)</figcaption></figure><p>Thankfully, each of our analytical algorithms has a unique name, and we can identify which one we want to run by specifying their names in the configuration. We tell the program which statistics we would like to see in the final report by typing the names of the associated algorithms into the config file. Now we only need something that takes these names from the config file, finds the functions with the same names in the business logic, and executes them (plus some code to put all results together in a report).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*hDKyf2UPCyUI8jl8XWdX7A.png" /><figcaption>Reflections map parameters from a configuration file living alongside the application to functions in the business logic. This allows for extension with little effort.</figcaption></figure><p>The part that finds the functions (given their names) is done by reflections. Reflections allow us to examine the business logic code structure and retrieve the actual function type given the function’s name.</p><p>This architecture allows us to easily extend out business logic without having to maintain another layer of our application or touch an existing code. The mapping of the configuration parameters to the analytics algorithms is done in a generic manner.</p><p>It also allows us to reconfigure the behavior of the application through an abstracted interface.</p><p>Note that we still need to recompile the whole application each time we extend the application by a new analytical algorithm. Plugin frameworks could help us avoid that, but this is beyond the scope of this article.</p><p>Of course, this architecture doesn’t come without drawbacks. Our reflect layer will just blindly retrieve functions and call them without knowing what these functions require or return. So we will need to implement all our analytical algorithms in a way that they can accept a generic type of input and return a generic type of output.</p><p>Each algorithm will return a different statistical model, but we need to return those models wrapped up in something the caller (that is, the reflect layer) can deal with. It can then send the wrapped-up model forward to the layer that produces the report which, of course, needs to be able to access the actual statistical model.</p><p>The way this is realized varies from language to language. We will look at (one way) to solve it in Go.</p><h3>Finding Functions by their Names</h3><p>The first step of getting from a plain YAML, JSON or XML configuration file to a callable algorithm (after loading the file into the application, of course) is to find a function in the software that matches the function name given in the configuration file.</p><p>Unfortunately, there is not really an intuitive way of retrieving a function residing in a package by its name in Go. We can’t just hand in a function name on one end and retrieve something callable on the other end.</p><p>However, it is possible to find a <em>method</em> <em>of a type</em> by its name.</p><p>A method in Go is a function that has a receiver, whereas a receiver can be any type that has been defined in the same package as the method.</p><pre>type Library struct {<br>    books []Book<br>}</pre><pre>func (l *Library) GetMostSoldBooks(startYear, endYear int) SoldStat {<br>    ...<br>}</pre><p>Here we define a type Library which is based on type struct. We now take the above defined function GetMostSoldBooks, pull the library parameter out, and turn it into a receiver type which turns the function into a method of the *Library type. On the other hand, *Library describes a pointer to Library.</p><p>This is practical, not only because Go offers a way to find methods of types by their names, but also because it allows us to tie all statistical algorithms to the *Library type. We will need an instance of this anyway in all these algorithms, as it contains all the data about the library we want to process in the algorithms.</p><p>Instead of passing the library as just another parameter to each function, we can use the library as a receiver and — in return — get stronger coupling. In this case, it makes our code cleaner. Each new statistical algorithm that is to be added to the application now must be a method of the *Library type.</p><p>Now let’s take a look at how we can actually use the reflect package to retrieve the above method if all we’ve got is its name.</p><pre>import &quot;reflect&quot;</pre><pre>m := reflect.ValueOf(&amp;Library{}).MethodByName(&quot;GetMostSoldBooks&quot;)</pre><p>First we need to take an instance of the receiver type (receiver type being *Library) and turn it into a reflect.Value by passing it to reflect.ValueOf(). On the returned value, we can then call MethodByName() with the name of the method we want to retrieve.</p><p>What we get in return is a callable function wrapped in reflect.Value which will accept exactly the parameters as we defined them in the method definition. Note that upon the call of this function, the instance of *Library we passed to reflect.ValueOf() will be used as the receiver type. This means <a href="https://golang.org/pkg/reflect/#Value.MethodByName">it is important</a> that you already passed the correct instance to the reflect.ValueOf()function.</p><p>To make the returned value m in the above example actually callable, we will need to cast it from reflect.Value to an actual function type with the correct signatures. This will look as follows:</p><pre>mCallable := m.Interface().(func(int, int) SoldStat)</pre><p>Note how we need to first turn it into an interface type and only then cast it to the function type.</p><h3>Making Methods Generic</h3><p>Ok, great. We now have a callable method which we retrieved by passing the function’s name to our application and letting reflections do the rest. But when it comes to calling the actual function, we’ve still got a bit of a problem.</p><p>We need to know the function’s signature in order to to be able to cast the reflect.Value returned by MethodByName() into a callable function. Since we have a lot of different analytical algorithms, chances are that the parameters they accept differ (we definitely don’t want to force a specific function signature onto developers who want to extend the application). This means that the method signatures vary and that we can’t just cast all values returned by the reflection into the exact same function type.</p><p>What we have to do is provide a generic function signature. We can do this by creating a wrapper method.</p><pre>func (l *Library) GetMostSoldBooksWrap(p GenericParams) Reportable {<br>    return l.GetMostSoldBooks(p.(*MostSoldBooksParams))<br>}</pre><p>Here we’ve got a wrapper method GetMostSoldBooksWrap for the concrete method GetMostSoldBooks. Like the concrete method, the wrapper is a method of type *Library. The difference is its signature. It accepts a generic prameter GenericParams and returns an instance of type Reportable. In its body, it invokes the concrete analytical method that processes the library data. Also new is the type MostSoldBooksParams which wraps the parameters for the concrete method.</p><p>Now, let’s see where those new types come from.</p><p>In order to be able to pass the GenericParams parameter to the concrete GetMostSoldBooks() method, the concrete method also needs to only accept one single parameter which we can cast the generic parameter to. We do this by changing the method signature of the concrete function to accept a *MostSoldBooksParams parameter.</p><p>This may first sound as though we are forcing a method signature upon the analytical algorithms after all, therefore contradicting the statement made above. And in some ways that is true. But in some way it isn’t, because MostSoldBooksParams is of type struct and can therefore contain multiple fields.</p><pre>type MostSoldBooksParams struct { <br>    startYear int<br>    endYear int<br>}</pre><pre>func (l *Library) GetMostSoldBooks(p *MostSoldBooksParams) SoldStat {<br>    ...<br>}</pre><p>As you can see, the parameter for the analytical method still incorporates both integer parameters startYear and endYear we had defined in the method signature originally. The method also still returns the concrete type SoldStat.</p><p>Let’s go back to the wrapper method.</p><p>As we now need to map the strings from the configuration file to the wrapper methods rather than the concrete methods, we need a wrapper for each analytical algorithm. It needs to be named so that it makes sense to add this name to the config file.</p><p>In this solution here, we name wrappers with &lt;concrete method name&gt;Wrap. In the config file, we can then just provide the same concrete method’s name and the reflect logic will append <em>“Wrap”</em> to the string before looking for the method.</p><p>The signatures, however, are the exact same for every wrapper function (otherwise they would be futile).</p><pre>type GenericParams interface { <br>   IsValid() (bool, string)<br>}</pre><p>The GenericParam parameter type is an interface. We declare one method IsValid() (bool, string) for this interface, meaning that every struct which defines this method automatically implements the GenericParams <a href="https://gobyexample.com/interfaces">interface</a>.</p><p>This is relevant because in our wrapper method, we cast the GenericParams interface to the concrete struct type MostSoldBooksParams . This only works if MostSoldBooksParams implements the GenericParams interface.<br>We therefore now provide a IsValid() method to our concrete parameter type.</p><pre>func (p *MostSoldBooksParams) IsValid() (bool, string) {<br> …<br> return true, “”<br>}</pre><p>The IsValid() function itself can be used to check the validity of the parameters passed to the concrete analytical method. We can call it at the very beginning of the method.</p><pre>func (l *Library) GetMostSoldBooks(p *MostSoldBooksParams) SoldStat<br>{<br>    if isValid, reason := p.IsValid(); !isValid {<br>        log.Fatalf(“\nParams invalid:: %s”, reason)<br>    }<br>    ...<br>}</pre><p>Lastly, we have the Reportable type, which is our generic return value.</p><pre>type Reportable interface { <br>    Report() HTMLStatisticReport <br>}</pre><p>Like the generic parameter type, Reportable is an interface. It declares one method Report() which will return a statistical report in HTML format.</p><p>Since our generic wrapper method directly returns the output of the concrete method, the concrete method’s return type must be of the generic wrapper method’s return type. This means that our SoldStat type, which is the type returned by the concrete analytical method, must implement the Reportabe interface.</p><p>We do this again by writing an implementation of the method declared by the interface.</p><pre>func (p SoldStat) Report() HTMLStatisticReport {<br>    ...create report...<br>}</pre><p>We will need to implement these methods for all different return types of all statistics algorithms so that the types can be returned by the generic wrappers. While this may appear to introduce a lot of overhead effort, converting the statistical output of each algorithm into a human-readable report is something that needs to be done either way.</p><p>Now that we have our generic design, we can go back to the reflections.</p><pre>m := reflect.ValueOf(library).MethodByName(&quot;GetMostSoldBooksWrap&quot;)<br>mCallable = m.Interface().(func(GenericParams) Reportable)</pre><p>These two lines of reflection can now be used to retrieve any analytical method wrapper by its name, whereby mCallable will be the callable wrapper method.</p><h3>Passing Parameters</h3><p>What’s missing are the method parameters. These will need to be parsed from the config file just like the method name and then passed to the wrapper method we retrieved through the reflection. This is where things become a bit convoluted.</p><pre>statistics: <br>    — statsMethodName: GetMostSoldBooks <br>      startYear: 1984<br>      endYear: 2018</pre><p>The above shows an example configuration file in YAML format. We have a root element statistics which maps to a list. Each element in the list is an analytical algorithm we want to run and include its output in the report. The elements consist of a key statsMethodName, with the name of the analytical method as the value, and one key per parameter with their corresponding values. Note that the names of the parameters must match the names of the fields in the parameter struct declared for the associated method. In this case here, the parameter struct is the one we declared before, namely MostSoldBooksParams, with fields startYear and endYear, both of which are of type integer.</p><p>What we need to add to our reflection now is the mapping of the strings (and other value types) defining the parameters, from the configuration file to the method parameter struct’s fields.</p><p>Since the concrete method parameter struct is in the concrete method’s signature but not in the signature of the wrapper method, we will need to retrieve the concrete method through the reflection logic in addition to the wrapper method.</p><pre>methodName := &quot;GetMostSoldBooks&quot; // taken from configuration file<br>conreteMethod := reflect.ValueOf(library).MethodByName(methodName)</pre><pre>wrapperName := fmt.Sprintf(&quot;%sWrap&quot;, methodName)<br>wrapperMethod := reflect.ValueOf(library).MethodByName(wrapperName)</pre><p>Next we need to access the parameter type passed to the <a href="https://golang.org/pkg/reflect/#Type">concrete method</a>.</p><pre>concreteMethodParamsType := conreteMethod.Type().In(0).Elem()</pre><p>concreteMethodParamsType will now hold the type of the method parameter struct. For the case of the GetMostSoldBooks this is MostSoldBooksParams.</p><p>In order to be able to retrieve the struct fields (which represent the parameters needed by the analytical algorithm) by their names (which are given in the configuration file), we need to create an instance of the method parameter struct type. We need both a pointer to the instance as well as the instance itself (as will be seen later).</p><pre>concreteMethodParamsPtr := reflect.New(concreteMethodParamsType)<br>concreteMethodParams := concreteMethodParamsPtr.Elem()</pre><p>At this stage, you can iterate over the keys of the stats element from the configuration file and map the parameter types one-by-one to the fields in the parameter (that is, retrieving the fields of the method parameter struct according to their names). To retrieve a field of a struct <a href="https://golang.org/pkg/reflect/#Value.FieldByName">by its name</a>, we can use reflect.FieldByName().</p><pre>parameterField := concreteMethodParams.FieldByName(configParam)</pre><p>Once we have the parameter fields retrieved, we can map the value given for this parameter in the configuration file to the actual field.</p><pre>if configValueInt, isInt := configValue.(int); isInt {<br>    parameterField.SetInt(int64(configValueInt)<br>)</pre><p>The above is for the case of integer values, but we could do the same for each value type we expect (in a trial and error fashion) for each parameter given in the configuration file. Setting the value on the parameter field here will also directly affect the method parameters struct, so we don’t need to explicitly alter concreteMethodParams in order to store the parameter value retrieved from the configuration file.</p><p>Lastly, just as we did with the wrapper method, we will cast the concreteMethodParams struct to a GenericParams type. Note that we need to use the pointer type there.</p><pre>wrapperParams := concreteMethodParamsPtr.Interface().(GenericParams)</pre><h3>Putting it all together</h3><p>Once we have our wrapper method and our generic method parameter, we can call the wrapper as follows.</p><pre>wrapperMethod(wrapperParams)</pre><p>As you can see, that’s just a normal function call. It does exactly the same as calling the wrapper would do without going through the reflection process.</p><p>Finally, you will just need a function that calls Report() on all of the return values from the invoked analytical method’s wrapper functions and puts the reports of each statistic into one coherent report file.</p><p>Now the question that you should ask is: <strong>Is this good code?</strong></p><p>My answer:<strong> I don’t know.</strong></p><p>What I <em>can</em> tell you is that it is an option worth exploring. Especially if you end up in a situation where you are in the need of a software design with similar requirements as the ones in this example — even if it’s just for the purpose of learning about reflections.</p><p>If you want to see the full code of an application using this design, check out: <a href="https://github.com/Demonware/harbor-analytics">https://github.com/Demonware/harbor-analytics</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4868b6cdb2dc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/a-practical-example-go-reflections-and-generic-designs-4868b6cdb2dc">Learn Go reflections and generic designs with a practical example</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Don’t blindly trust the Docker ping]]></title>
            <link>https://medium.com/hackernoon/dont-blindly-trust-the-docker-ping-fce462944e9c?source=rss-11675b713da9------2</link>
            <guid isPermaLink="false">https://medium.com/p/fce462944e9c</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[mac]]></category>
            <dc:creator><![CDATA[David Rieger]]></dc:creator>
            <pubDate>Wed, 09 Aug 2017 17:03:04 GMT</pubDate>
            <atom:updated>2019-04-29T10:16:32.801Z</atom:updated>
            <content:encoded><![CDATA[<p>I was playing around with the good old ping command in an <a href="https://hub.docker.com/_/alpine/">alpine</a> <a href="https://hackernoon.com/tagged/docker">Docker</a> container today. I wanted to perform a little load test for another service so I experimented with different package sizes (ping -s &lt;size in byte&gt;), which caused me quite a bit of MTU-related frustration (but that’s a different story).</p><p>Upon googling about pings from docker, I stumbled across <a href="https://forums.docker.com/t/ping-from-within-a-container-does-not-actually-ping">this forum post</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*GdWcZNDO5Q4cfNdzpvPpxg.png" /><figcaption>Header of forum post about misbehaving pings in docker containers on MAC</figcaption></figure><p>I will let you read the post yourself instead of copying everything in here, but the essence is: <strong>ping packets may return to you even if you send the pings to a non-existing host</strong>.</p><p>And it’s true. I took a random IP and made sure it’s not actually ping-able from my desktop.</p><pre>$ ping 11.12.13.14 -c 5<br>PING 11.12.13.14 (11.12.13.14): 56 data bytes<br>Request timeout for icmp_seq 0<br>Request timeout for icmp_seq 1<br>Request timeout for icmp_seq 2<br>Request timeout for icmp_seq 3<br>^C<br>--- 11.12.13.14 ping statistics ---<br>5 packets transmitted, 0 packets received, 100.0% packet loss</pre><p>Then ran it from inside a Docker container.</p><pre>$ docker run alpine ping 11.12.13.14 -c 5<br>PING 11.12.13.14 (11.12.13.14): 56 data bytes<br>64 bytes from 11.12.13.14: seq=0 ttl=37 time=0.447 ms<br>64 bytes from 11.12.13.14: seq=1 ttl=37 time=0.469 ms<br>64 bytes from 11.12.13.14: seq=2 ttl=37 time=0.524 ms<br>64 bytes from 11.12.13.14: seq=3 ttl=37 time=0.476 ms<br>64 bytes from 11.12.13.14: seq=4 ttl=37 time=0.461 ms</pre><pre>--- 11.12.13.14 ping statistics ---<br>5 packets transmitted, 5 packets received, 0% packet loss<br>round-trip min/avg/max = 0.447/0.475/0.524 ms</pre><p>This is bad news, because it means you can’t really trust ping anymore. You might have a health-check that tests connectivity to one of your production services through pings and keeps reporting green even though the service is down.</p><p>To make matters worse, it doesn’t happen for all fake IPs and the forum post was created over a year ago.</p><p>The good news is, this only happens for Docker on <a href="https://hackernoon.com/tagged/mac">MAC</a> (maybe Windows as well), but not Linux.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*EIRqe157rE_qQfrWSIhSWg.png" /><figcaption>Screenshot of the “ghost ping”.</figcaption></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fce462944e9c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/dont-blindly-trust-the-docker-ping-fce462944e9c">Don’t blindly trust the Docker ping</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automated pre-commit code checks with and without Docker]]></title>
            <link>https://frontside.medium.com/automated-pre-commit-code-checks-with-and-without-docker-b4a6ccf249ce?source=rss-11675b713da9------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4a6ccf249ce</guid>
            <category><![CDATA[static-code-analysis]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[ansible]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[David Rieger]]></dc:creator>
            <pubDate>Sat, 13 May 2017 10:14:48 GMT</pubDate>
            <atom:updated>2017-05-13T11:47:36.900Z</atom:updated>
            <content:encoded><![CDATA[<p>Continuous Integration/Deployment pipelines are great. All you have to do is click a button and your code will be built, tested and perhaps deployed.</p><p>But pipelines may need some time to run. It could take minutes until your CI system even picks up a queuing job. Seeing a pipeline then fail because of a missing colon in one of your yaml files after 10 minutes of waiting is no fun.</p><p>If you have a proper IDE or even just a text editor with some nice plugins, you will catch such syntax errors straight away. But the temptation to just quickly open a file in a conventional vi and add a line can often overpower you and that’s when the mistakes happen.</p><p>My solution to this are static code checks, performed automatically upon git commit through the use of git hooks.</p><p>Git hooks are a great way of integrating repetitive automatable tasks into your development workflow. They are basically nothing more than scripts that are being run when a certain git command is entered, but they can be very powerful.</p><p>There are various types of git hooks, triggered by actions such as clone, pull, merge, commit, or push<a href="https://git-scm.com/book/gr/v2/Customizing-Git-Git-Hooks">[1]</a>. We will for now be focusing on the pre-commit hook which is triggered by a git commit before the editor for entering the commit message is opened.</p><h4>Got an example?</h4><p>Surely. I use Ansible a fair bit and Ansible playbooks are yaml files. Ansible’s CLI offers a check for its playbooks which will validate more than just the yaml structure (but that is out of the scope for this article).</p><p>What I wanted now, was for this check to be run for each playbook that has changed since the last commit and is now about to be committed. I wrote a little script<a href="http://github.com/frontside/pre-commit-code-checks.git">[2]</a> that finds all added and modified playbooks and triggers a check for each of them. All I needed to do now was copy this script to .git/hooks/pre-commit and make it executable. Voila, the check now runs before every commit. If it fails it will show me the error and abort the commit.</p><h4>Ok, I get it, Ansible checks triggered by git hooks, but what has Docker to do with that?</h4><p>Performance and portability are the key-words.</p><p>Instead of running all the checks for the playbooks sequentially, I start a bunch of docker containers and perform the checks inside of them. The playbook:container ratio is 1:1.</p><p>This decreases the time needed for checking, and allows me to not wait all too long before I can enter the commit message, so I won’t be tempted to skip the checks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*NCJtbUbQ5mTgkUXgqmTcSw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*pW3PF7qgrET7_GYLY-6AcQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*xx4KjShmQYI7lA92HhBhWg.png" /><figcaption>These are the results from my code-check benchmarks. The orange line shows the amount of time in seconds (y-axis) it took for n playbooks (x-axis) to be checked sequentially without Docker. The blue line shows the same, but with the checks happening in n concurrently running docker containers.</figcaption></figure><p>Except for the cases where you only have to perform one or two checks, running containers shows a significant performance improvement. But even for those cases where I only have one playbook, the performance of running the checks without docker is hardly significant.</p><p>The second reason for using containers is, that I don’t need to take all too much care of the tools on my machine. If my colleague clones my repo they may not have Ansible installed on the desktop, but if we use containers this doesn’t bother us at all since Ansible will be installed in there.</p><h4>Is that speed really all just Docker?</h4><p>Well, yes and no. Unfortunately starting a docker container even in detached mode takes a bit of time until it returns a container ID, which we need in order to be able to get the logs and the return-codes from the checks.</p><p>To speed things up a bit, I wrote a tiny go application which will directly access the docker API and combine Docker with Go’s phenomenal multiprocessing capabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*1slE_EJaeRradQLSpdBO6Q.png" /><figcaption>Control Flow Diagram of automated Ansible playbook checks triggered by a git commit and executed with docker containers</figcaption></figure><h4>The bad news</h4><p>Yes, running these checks in parallel makes things faster. However, a pre-commit check should be something simple and lightweight. Maintaining a separate tool is probably not worth the effort.</p><p>I decided to get rid of the go application again and use docker-compose instead. The results are not good unfortunately (you can find the benchmark results in the repository <a href="https://github.com/frontside/pre-commit-code-checks.git">[2]</a>). Especially if we only have one or two playbooks to commit (which, in my case, is most of the time), the sequential checks are significantly quicker than the ones using docker-compose.</p><p>The bottom line is: Docker can, if implemented properly, improve the performance of these checks significantly, but there’s a good chance, the complexity of building and maintaining such an implementation outweighs the benefits.</p><p>[1] <a href="https://git-scm.com/book/gr/v2/Customizing-Git-Git-Hooks">https://git-scm.com/book/gr/v2/Customizing-Git-Git-Hooks</a><br>[2] <a href="http://github.com/frontside/pre-commit-code-checks.git">https://github.com/frontside/pre-commit-code-checks.git</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4a6ccf249ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting rid of Docker plain text credentials]]></title>
            <link>https://medium.com/hackernoon/getting-rid-of-docker-plain-text-credentials-88309e07640d?source=rss-11675b713da9------2</link>
            <guid isPermaLink="false">https://medium.com/p/88309e07640d</guid>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[David Rieger]]></dc:creator>
            <pubDate>Wed, 08 Mar 2017 20:51:47 GMT</pubDate>
            <atom:updated>2019-04-29T10:17:29.866Z</atom:updated>
            <content:encoded><![CDATA[<p>You might not be aware of it, but the <a href="https://hackernoon.com/tagged/docker">docker</a> engine stores the credentials you use with docker login in plain text in a file called $HOME/.docker/config.json. Well, granted, it’s not ASCII, it’s base64, which may look like encryption on first glance, <strong>but it’s not</strong>. Base64 is a scheme for encoding, not encryption. You can simply copy the base64 string and convert it to ASCII in a matter of seconds.</p><h4>OMG, I’m strongly concerned about the secrecy of my passwords, what should I do?</h4><p>I’m glad you asked. Thankfully, docker offers <a href="https://github.com/docker/docker-credential-helpers">credential helpers</a>, which will use your operating system’s native <a href="https://hackernoon.com/tagged/credential">credential</a> store instead of config.json.</p><p><strong>Download the archive</strong> containing the helper for your operating system from <a href="https://github.com/docker/docker-credential-helpers/releases">Github</a> and <strong>unpack it to </strong><strong>/usr/local/bin</strong>. Don’t forget to <strong>make it executable</strong>.</p><p>If you are on <em>Linux</em> this should work for you to install verison 0.4.2 of the helper (you will need to be root):</p><pre>wget <a href="https://github.com/docker/docker-credential-helpers/releases/download/v0.4.2/docker-credential-secretservice-v0.4.2-amd64.tar.gz">https://github.com/docker/docker-credential-helpers/releases/download/v0.4.2/docker-credential-secretservice-v0.4.2-amd64.tar.gz</a> &amp;&amp; tar -xf <a href="https://github.com/docker/docker-credential-helpers/releases/download/v0.4.2/docker-credential-secretservice-v0.4.2-amd64.tar.gz">docker-credential-secretservice-v0.4.2-amd64.tar.gz</a> &amp;&amp; chmod +x docker-credential-secretservice &amp;&amp; mv docker-credential-secretservice /usr/local/bin/</pre><p>Once that’s done, <strong>open </strong><strong>~/.docker/config.json and add a </strong><strong>credsStore</strong> key to the JSON object’s root. The <strong>value will be the name of the credential storage service</strong>. This is basically the word after the last hyphen of the executable you just installed. For Linux, the executable is called docker-credential-secretservice, so the service name is secretservice.</p><p>If you are on <em>Linux</em> and trust my sed skills you could try and run</p><pre>sed -i &#39;0,/{/s/{/{\n\t&quot;credsStore&quot;: &quot;secretservice&quot;,/&#39; ~/.docker/config.json</pre><p>From this point forward, docker will use the external service to store your credentials for docker login &lt;url&gt;. To get rid of the ones that are already in the file, simply docker logout &lt;url&gt;.</p><p><strong>Reference<br></strong><a href="https://docs.docker.com/engine/reference/commandline/login/#privileged-user-requirement">Official Documentation on docker login.</a></p><blockquote><a href="http://bit.ly/Hackernoon">Hacker Noon</a> is how hackers start their afternoons. We’re a part of the <a href="http://bit.ly/atAMIatAMI">@AMI</a>family. We are now <a href="http://bit.ly/hackernoonsubmission">accepting submissions</a> and happy to <a href="/service/mailto:partners@amipublications.com">discuss advertising &amp; sponsorship</a> opportunities.</blockquote><blockquote>To learn more, <a href="https://goo.gl/4ofytp">read our about page</a>, <a href="http://bit.ly/HackernoonFB">like/message us on Facebook</a>, or simply, <a href="https://goo.gl/k7XYbx">tweet/DM @HackerNoon.</a></blockquote><blockquote>If you enjoyed this story, we recommend reading our <a href="http://bit.ly/hackernoonlatestt">latest tech stories</a> and <a href="https://hackernoon.com/trending">trending tech stories</a>. Until next time, don’t take the realities of the world for granted!</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88309e07640d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/getting-rid-of-docker-plain-text-credentials-88309e07640d">Getting rid of Docker plain text credentials</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>