Sunday, November 17, 2019

Fedora 30 Add another port for ssh'ing to get around some wifi filters

Some ISP's that offer free wifi will not allow you to ssh. To get around this you can set your ssh server to use another port like 8080.

For Fedora 30

1) sudo vim /etc/ssh/sshd_config

Change

#Port 22
to
Port 22
Port 8080


# This allows two ports to connect to ssh

2) Update selinux to allow ssh on port 8080

sudo semanage port -m -t ssh_port_t -p tcp 8080

If you use -a you will get an error like
ValueError: Port tcp/8080 already defined

If you -d you will get another error like
ValueError: Port tcp/8080 is defined in policy, cannot be deleted

Use this to check:

sudo semanage port -l | grep 8080
http_cache_port_t              tcp      8080, 8118, 8123, 10001-10010
ssh_port_t                     tcp      8080, 22

Saturday, August 17, 2019

Create an interface array consisting of a generic struct type in golang

I was looking at how to get a result set from a golang sql query. It seemed that a lot of the examples explicitly defined the fields or declared a struct that are passed into the Scan() method such as:

var id int
var name string
err = rows.Scan(&id, &name)
// or
row = MyStruct{}

err = rows.Scan(&row.Id, &row.Name)

This seemed like a lot of repetition if every query required this logic. My next thought was to see if I could pass in a struct, use reflect to obtain the fields and return a slice of values.

Here are two examples, the first one uses uses append and requires type assertion to access the fields. The second example uses reflect.append and each field can be accessed directly from the element.

Note: Additional checks should be added, such as making sure the address of the object is passed in.

First
package main

import (
    "fmt"
    "reflect"
)

type MyStruct struct {
    Id int
    Name string
}

func main() {
    me := MyStruct{}
    result := doIt(&me)

    for _, v := range result {
        fmt.Printf("%d %s\n", v.(MyStruct).Id, v.(MyStruct).Name)
    }
}

func doIt(genericStruct interface{}) []interface{} {
    params := []interface{}{}
    var myStruct reflect.Value

    structType := reflect.TypeOf(genericStruct).Elem()

    // First Element
    myStruct = reflect.New(structType).Elem()
    myStruct.FieldByName("Id").SetInt(1)
    myStruct.FieldByName("Name").SetString("one")
    fmt.Printf("%#v\n", myStruct)

    params = append(params, myStruct.Interface())

    // Second Element
    myStruct = reflect.New(structType).Elem()
    myStruct.FieldByName("Id").SetInt(2)
    myStruct.FieldByName("Name").SetString("two")
    fmt.Printf("%#v\n", myStruct)

    params = append(params, myStruct.Interface())

    return params
}

Second
package main

import (
    "fmt"
    "reflect"
)

type MyStruct struct {
    Id int
    Name string
}

func main() {
    myStruct := []MyStruct{}
    doIt(&myStruct)

    for _, v := range myStruct {
        fmt.Printf("%d %s\n", v.Id, v.Name)
    }
}

func doIt(genericStructArray interface{}) {
    var myStruct reflect.Value

    genericValue := reflect.ValueOf(genericStructArray).Elem()
    genericType := genericValue.Type().Elem()

    // First Element
    myStruct = reflect.New(genericType).Elem()
    myStruct.FieldByName("Id").SetInt(1)
    myStruct.FieldByName("Name").SetString("one")
    fmt.Printf("%#v\n", myStruct)

    genericValue.Set(reflect.Append(genericValue, myStruct))

    // Second Element
    myStruct = reflect.New(genericType).Elem()
    myStruct.FieldByName("Id").SetInt(2)
    myStruct.FieldByName("Name").SetString("two")
    fmt.Printf("%#v\n", myStruct)

    genericValue.Set(reflect.Append(genericValue, myStruct))
}

Output (same for both)
main.MyStruct{Id:5, Name:"one"}
main.MyStruct{Id:2, Name:"two"}
5 one
2 two

Saturday, June 8, 2019

Learning middleware patterns in Golang

Middlewares are often applied using a wrapping a method wrapping pattern (chain of responsibility design pattern). To better understand how to do this in golang, I've started with the Handler interface and created a HandlerFunc that mimics the HandlerFunc in https://golang.org/src/net/http/server.go except I've replaced the args with (context string). This allowed me to trace the order that middlewares access the current context.

func (r *Request) Context() context.Context

Some useful links that helped guide me.
https://www.calhoun.io/why-cant-i-pass-this-function-as-an-http-handler/
https://www.alexedwards.net/blog/making-and-using-middleware
https://github.com/justinas/alice Ended with an implementation that resembles this. Thx!

Update July 2019: Middleware args changed to Handler instead of HandlerFunc

package main

import "fmt"

// HandlerFunc, ServeHTTP match the go standard libs except
// (w ResponseWriter, r *Request) has been replaced by (context string).
// We treat this as a buffer that we can read from add values to.
// Analagous to reading GET/POST args from Request and adding
// Information to Request.context()
// https://golang.org/src/net/http/server.go

// This implements Handler interface because it matches signature, meaning it has a
// ServerHTTP method with the same argument types

type Handler interface {
    ServeHTTP(context string)
}

type HandlerFunc func(context string)

func (f HandlerFunc) ServeHTTP(context string) {
    f(context)
}

func baseHandler(h Handler) Handler {
    fmt.Println("Before return baseHandler")
    return HandlerFunc(func(context string) {
        fmt.Println("Before baseHandler")
        context = context + " base"
        h.ServeHTTP(context) // call ServeHTTP on the original handler
        fmt.Println("After baseHandler")
    })
}

func first(h Handler) Handler {
    fmt.Println("Before return first")
    return HandlerFunc(func(context string) {
        fmt.Println("Before first")
        context = context + " first"
        h.ServeHTTP(context) // call ServeHTTP on the original handler
        fmt.Println("After first")
    })
}

func second(h Handler) Handler {
    fmt.Println("Before return second")
    return HandlerFunc(func(context string) {
        fmt.Println("Before second")
        context = context + " second"
        h.ServeHTTP(context) // call ServeHTTP on the original handler
        fmt.Println("After second")
    })
}

func IndexEndPoint(s string) {
    fmt.Println("Index EndPoint: ", s)
}

type Middleware func(Handler) Handler

type MiddlewareStack struct {
    middlewares []Middleware
}

func NewMiddlewareStack(middlewares ...Middleware) MiddlewareStack {
    return MiddlewareStack{middlewares: middlewares}
}

// The middleware wrap pattern eg. second(first(baseHandler(IndexEndPoint))
// means you need to find the deepest method and work backwards -
// baseHandler, then first, then second.
// This implementation stores the middlewares in an array and can mutate the
// values beginning with the lowest to highest index; which has some
// readability benefits.
func (ms *MiddlewareStack) EndPoint(endPoint HandlerFunc) Handler {
    var h Handler

    // first middlware in array can access the context first
    for i := len(ms.middlewares) - 1; i >= 0; i-- {
        mw := ms.middlewares[i]
        // for _, mw := range ms.middlewares {
        if h == nil {
            h = mw(endPoint)
        } else {
            h = mw(h)
        }
    }

    return h
}

func main() {

    // middleware function wrapping
    // Output: Index EndPoint: start second first base
    f := second(first(baseHandler(HandlerFunc(IndexEndPoint))))
    f.ServeHTTP("start")

    /*
        // array of middleware
        // Another version of above, but storing in an array
        middleWares := []MiddleWare{baseHandler, first, second}

        var hFunc HandlerFunc
        for _, mw := range middleWares {
            if hFunc == nil {
                hFunc = mw(IndexEndPoint)
            } else {
                hFunc = mw(hFunc)
            }
        }

        hFunc.ServeHTTP("start")
    */

    // middleware struct
    // Index EndPoint: start base first second
    middlewareStack := NewMiddlewareStack(baseHandler, first, second)

    hFunc := middlewareStack.EndPoint(IndexEndPoint)

    hFunc.ServeHTTP("start")
}