Doing CORS in Go with Gin and JSON

Basics Hello folks. This will be a quick post about how to do CORS with jQuery, Gin in Go with a very simple ajax GET and Json. I’m choosing JSON here because basically I don’t really like JSONP. And actually, it’s not very complicated to do CORS, it’s just hidden enough so that it doesn’t become transparent. First, what is CORS? It’s Cross-Platform Resource Sharing. It has been invented so that without your explicit authorization in the header of a request, Javascript can’t reach outside of your domain and be potentially harmful to your visitors. ...

February 2, 2016 · 4 min · hannibal

My Journey in advent of code

Hello folks. I wanted to share with you my tale of working through the problems with Advent Of Code. It is a nice tale and there are a few things I learned from it, especially in Go, since I used that solve all of the problems. So, let’s get started. Solving the problems The most important lesson I learned while doing these exercises was, how to solve these problems. A couple of them were simple enough to not have to over think it, but most of them got very tricky. I could have gone with a brute force attempt, but as we see later, that wasn’t always a very good solution. And people who used that, actually just got lucky finding their solutions. ...

January 22, 2016 · 8 min · hannibal

Improving performance with byte slice and int map

Hello Folks. Today I would like to share with you my little tale of refactoring my solution to Advent Of Code Day 13. It’s a lovely tale of action, adventure, drama, and comedy. Let’s being with my first iteration of the problem. package main import ( "bufio" "fmt" "math" "os" "strconv" "strings" "github.com/skarlso/goutils/arrayutils" ) var seatingCombinations = make([][]string, 0) var table = make(map[string][]map[string]int) var keys = make([]string, 0) //Person a person type Person struct { // neighbour *Person name string like int } func main() { file, _ := os.Open("input.txt") defer file.Close() scanner := bufio.NewScanner(file) for scanner.Scan() { line := scanner.Text() split := strings.Split(line, " ") like, _ := strconv.Atoi(split[3]) //If lose -> * -1 if split[2] == "lose" { like *= -1 } table[split[0]] = append(table[split[0]], map[string]int{strings.Trim(split[10], "."): like}) if !arrayutils.ContainsString(keys, split[0]) { keys = append(keys, split[0]) } } generatePermutation(keys, len(keys)) fmt.Println("Best seating efficiency:", calculateSeatingEfficiancy()) } func generatePermutation(s []string, n int) { if n == 1 { news := make([]string, len(s)) copy(news, s) seatingCombinations = append(seatingCombinations, news) } for i := 0; i < n; i++ { s[i], s[n-1] = s[n-1], s[i] generatePermutation(s, n-1) s[i], s[n-1] = s[n-1], s[i] } } func calculateSeatingEfficiancy() int { bestSeating := math.MinInt64 for _, v := range seatingCombinations { calculatedOrder := 0 for i := range v { left := (i - 1) % len(v) //This is to work around the fact that in Go //modulo of a negative number will not return a positive number. //So -1 % 4 will not return 3 but -1. In that case we add length. if left < 0 { left += len(v) } right := (i + 1) % len(v) // fmt.Printf("Left: %d; Right: %d\n", left, right) leftLike := getLikeForTargetConnect(v[i], v[left]) rightLike := getLikeForTargetConnect(v[i], v[right]) // fmt.Printf("Name: %s; Left:%d; Right:%d\n", v[i], leftLike, rightLike) calculatedOrder += leftLike + rightLike } // fmt.Printf("Order for: %v; Calc:%d\n", v, calculatedOrder) if calculatedOrder > bestSeating { bestSeating = calculatedOrder } } return bestSeating } func getLikeForTargetConnect(name string, neighbour string) int { neighbours := table[name] for _, t := range neighbours { if v, ok := t[neighbour]; ok { return v } } return 0 } This is quiet large. And takes a bit of explaining. So what is happening here? We are putting the names which correspond with numbers and neighbours into a map which has a map as a value. The map contains seating information for a person. For example, next to Alice, a bunch of people can sit, and they have a certain relationship to Alice, represented by a number. ...

January 5, 2016 · 7 min · hannibal

Byte arrays and Channels

Hi folks and a Happy new Year! Today, I would like to show you some interesting things you can do with channels. Consider the following simple example. package main import "fmt" func main() { generatedPassword := make(chan int, 100) correctPassword := make(chan int) defer close(generatedPassword) defer close(correctPassword) go passwordIncrement(generatedPassword) go checkPassword(generatedPassword, correctPassword) pass := <-correctPassword fmt.Println(pass) } func checkPassword(input <-chan int, output chan<- int) { for { p := <-input //Introduce lengthy operation here // time.Sleep(time.Second) fmt.Println("Checking p:", p) if p > 100000 { output <- p } } } func passwordIncrement(out chan<- int) { p := 0 for { p++ out <- p } } The premise is as follows. It launches two go routines. One, which generates passwords, and an other which checks for validity. The two routines talk to each other through the channel generatedPassword. That’s the providing connections between them. The channel correctPassword provides output for the checkPassword routine. ...

January 1, 2016 · 4 min · hannibal

Use Byte Array Instead of Strings

Hello Folks. This is just a quick post on the topic and a reminder for myself and everybody to ALWAYS USE []BYTE INSTEAD OF STRINGS. []Byte is marginally faster than a simple Strings. In fact, I would say using []byte should be the standard instead of strings. Sample code: package solutions import "fmt" const ( //INPUT input INPUT = "1321131112" //LIMIT limit LIMIT = 50 ) //LookAndSay translates numbers according to Look and Say algo func LookAndSay(s string, c chan string) { charCount := 1 look := "" for i := range s { if i+1 < len(s) { if s[i] == s[i+1] { charCount++ } else { look += fmt.Sprintf("%d%s", charCount, string(s[i])) charCount = 1 } } else { look += fmt.Sprintf("%d%s", charCount, string(s[i])) } } c <- look } //GetLengthOfLookAndSay Retrieve the Length of a lookandsay done Limit times func GetLengthOfLookAndSay() { c := make(chan string, 0) go LookAndSay(INPUT, c) finalString := <-c for i := 0; i <= LIMIT-2; i++ { go LookAndSay(finalString, c) finalString = <-c // fmt.Println(finalString) } fmt.Println("Lenght of final String:", len(finalString)) } This, with the limit raised to 50 run for ~1 hour. Even with the routines although they were just for show since they had to wait for each others input. ...

December 29, 2015 · 2 min · hannibal

Use Byte Slice Instead of Strings

Hello Folks. This is just a quick post on the topic and a reminder for myself and everybody to ALWAYS USE []BYTE INSTEAD OF STRINGS. []Byte is marginally faster than a simple Strings. In fact, I would say using []byte should be the standard instead of strings. Sample code: package solutions import "fmt" const ( //INPUT input INPUT = "1321131112" //LIMIT limit LIMIT = 50 ) //LookAndSay translates numbers according to Look and Say algo func LookAndSay(s string, c chan string) { charCount := 1 look := "" for i := range s { if i+1 < len(s) { if s[i] == s[i+1] { charCount++ } else { look += fmt.Sprintf("%d%s", charCount, string(s[i])) charCount = 1 } } else { look += fmt.Sprintf("%d%s", charCount, string(s[i])) } } c <- look } //GetLengthOfLookAndSay Retrieve the Length of a lookandsay done Limit times func GetLengthOfLookAndSay() { c := make(chan string, 0) go LookAndSay(INPUT, c) finalString := <-c for i := 0; i <= LIMIT-2; i++ { go LookAndSay(finalString, c) finalString = <-c // fmt.Println(finalString) } fmt.Println("Lenght of final String:", len(finalString)) } This, with the limit raised to 50 run for ~1 hour. Even with the routines although they were just for show since they had to wait for each others input. ...

December 29, 2015 · 2 min · hannibal

Recursive Letter Frequency Count

Hello everybody! I wanted to do a sort post about word frequency count. I did it many times now and I was curious as how a recursive solution would perform as opposed to looping. So I wrote it up quickly and added a few benchmarks with different sized data. First…. The code: var freqMap = make(map[string]int, 0) func countLettersRecursive(s string) string { if len(s) == 0 { return s } freqMap[string(s[0])]++ return countLettersRecursive(s[1:]) } func countLettersLoop(s string) { for _, v := range s { freqMap[string(v)]++ } } Very simple. The first run with a small sample: “asdfasdfasdfasdfasdf” ...

December 23, 2015 · 1 min · hannibal

Go Development Environment

Hello folks. Here is a little something I’ve put together, since I’m doing it a lot. Go Development Environment If I have a project I’d like to contribute, like GoHugo, I have to setup a development environment, because most of the times, I’m on a Mac. And on OSX things work differently. I like to work in a Linux environment since that’s what most of the projects are built on. So here you go. Just download the files, and say vagrant up which will do the magic. ...

December 8, 2015 · 1 min · hannibal

Welcome To My New Blog

Hello Folks Welcome to my new blog. I decided to move away for a number of reasons, but setting up a static page blog site is very cool if you don’t directly use a database. Since posts are just posts and I have a different way of hosting images, this really was just a matter of time. And Hugo / Github pages provided the tools which made this move possible. Also, I love writing this post in Markdown. I always liked the formatting rules of it, so this is quiet the blast. ...

December 7, 2015 · 1 min · hannibal

Go JIRA API client

Hi folks. So, I was playing around and created a client for JIRA written in Go. It was nice to do some JSON transformation. And sending POSTS was really trivial. It’s still in it’s infancy and I have a couple of more features I want to implement, but, here is the code. package main import ( "bytes" "encoding/json" "flag" "fmt" "io/ioutil" "log" "net/http" "os" "github.com/BurntSushi/toml" ) var configFile = "~/.jira_config.toml" var parameter string var flags struct { Comment string Description string IssueKey string Priority string Resolution string Title string Project string } //Issue is a representation of a Jira Issue type Issue struct { Fields struct { Project struct { Key string `json:"key"` } `json:"project"` Summary string `json:"summary"` Description string `json:"description"` Issuetype struct { Name string `json:"name"` } `json:"issuetype"` Priority struct { ID string `json:"id"` } `json:"priority"` } `json:"fields"` } //Transition defines a transition json object. Used for starting, stoppinp //generally for state stranfer type Transition struct { Fields struct { Resolution struct { Name string `json:"name"` } `json:"resolution"` } `json:"fields"` Transition struct { ID string `json:"id"` } `json:"transition"` } //Credentials a representation of a JIRA config which helds API permissions type Credentials struct { Username string Password string URL string } func init() { flag.StringVar(&flags.Comment, "m", "Default Comment", "A Comment when changing the status of an Issue.") flag.StringVar(&flags.Description, "d", "Default Description", "Provide a description for a newly created Issue.") flag.StringVar(&flags.Priority, "p", "2", "The priority of an Issue which will be set.") flag.StringVar(&flags.IssueKey, "k", "", "Issue key of an issue.") flag.StringVar(&flags.Resolution, "r", "Done", "Resolution when an issue is closed. Ex.: Done, Fixed, Won't fix.") flag.StringVar(&flags.Title, "t", "Default Title", "Title of an Issue.") flag.StringVar(&flags.Project, "o", "IT", "Define a Project to create a ticket in.") flag.Parse() } func (cred *Credentials) initConfig() { if _, err := os.Stat(configFile); err != nil { log.Fatalf("Error using config file: %v", err) } if _, err := toml.DecodeFile(configFile, cred); err != nil { log.Fatal("Error during decoding toml config: ", err) } } func main() { if len(flag.Args()) < 1 { log.Fatal("Please provide an action to take. Usage information:") } parameter = flag.Arg() switch parameter { case "close": closeIssue(flags.IssueKey) case "start": startIssue(flags.IssueKey) case "create": createIssue() } } func closeIssue(issueKey string) { if issueKey == "" { log.Fatal("Please provide an issueID with -k") } fmt.Println("Closing issue number: ", issueKey) var trans Transition //TODO: Add the ability to define a comment for the close reason trans.Fields.Resolution.Name = flags.Resolution trans.Transition.ID = "2" marhsalledTrans, err := json.Marshal(trans) if err != nil { log.Fatal("Error occured when marshaling transition: ", err) } fmt.Println("Marshalled:", trans) sendRequest(marhsalledTrans, "POST", issueKey+"/transitions?expand=transitions.fields") } func startIssue(issueID string) { if issueID == "" { log.Fatal("Please provide an issueID with -i") } fmt.Println("Starting issue number:", issueID) } func createIssue() { fmt.Println("Creating new issue.") var issue Issue issue.Fields.Description = flags.Description issue.Fields.Priority.ID = flags.Priority issue.Fields.Summary = flags.Title issue.Fields.Project.Key = flags.Project issue.Fields.Issuetype.Name = "Task" marshalledIssue, err := json.Marshal(issue) if err != nil { log.Fatal("Error occured when Marshaling Issue:", err) } sendRequest(marshalledIssue, "POST", "") } func sendRequest(jsonStr []byte, method string, url string) { cred := &Credentials{} cred.initConfig() fmt.Println("Json:", string(jsonStr)) req, err := http.NewRequest(method, cred.URL+url, bytes.NewBuffer(jsonStr)) req.Header.Set("Content-Type", "application/json") req.SetBasicAuth(cred.Username, cred.Password) client := &http.Client{} resp, err := client.Do(req) if err != nil { panic(err) } defer resp.Body.Close() fmt.Println("response Status:", resp.Status) fmt.Println("response Headers:", resp.Header) body, _ := ioutil.ReadAll(resp.Body) fmt.Println("response Body:", string(body)) } It can also be found under my github page: GoJira Github. ...

November 20, 2015 · 3 min · hannibal