oinume journal

Scratchpad of what I learned

Go Tip: Don't take the address of loop variable

stackoverflow.com

If you take the address of loop variable, it may cause a bug which all values are same. You might expect following program prints 5 10 15 but it prints 15 15 15. That’s because loop variable v is initialized just once.

package main

import "fmt"

func main() {
    coll := []int{5, 10, 15}
    for _, v := range toPointers(coll) {
        fmt.Printf("%v ", *v)
    }
}

func toPointers(ints []int) []*int {
    pointers := make([]*int, len(ints))
    for i, v := range ints {
        pointers[i] = &v // XXX: mistake
    }
    return pointers
}

You can get expected result if you write like this:

package main

import "fmt"

func main() {
    coll := []int{5, 10, 15}
    for _, v := range toPointers(coll) {
        fmt.Printf("%v ", *v)
    }
}

func toPointers(ints []int) []*int {
    pointers := make([]*int, len(ints))
    for i, _ := range ints {
        pointers[i] = &ints[i]
    }
    return pointers
}

First loaded configuration becomes default_server in nginx

How nginx processes a request

server {
    listen      80;
    server_name example.org www.example.org;
    ...
}

server {
    listen      80;
    server_name example.net www.example.net;
    ...
}

server {
    listen      80;
    server_name example.com www.example.com;
    ...
}
In this configuration nginx tests only the request’s header field “Host” to determine which server the request should be routed to. If its value does not match any server name, or the request does not contain this header field at all, then nginx will route the request to the default server for this port. In the configuration above, the default server is the first one — which is nginx’s standard default behaviour.

I didn't know this behaviour and I should always add default_server to prevent someone from misunderstanding like this.

server {
    listen      80 default_server;
    server_name _;
}

Making an enviroment to learn ES6 with babel

This is a just memo for me who is a beginner of front-end development.

First of all, install nodejs v4.4.0.

$ brew install homebrew/versions/node4-lts
$ node -v
v4.4.0

Put package.json into a current directory. DO NOT forget to add babel-preset-es2015.

{
  "name": "hello",
  "version": "1.0.0",
  "engines": {
    "node": "4.4.0",
    "npm": "3.8.2"
  },
  "devDependencies": {
    "babel-cli": "^6.0.0",
    "babel-preset-es2015": "^6.6.0"
  }
}

Run npm install

$ npm install 

Put .babelrc to tell babel using es2015 preset.

echo '{ "presets": ["es2015"] }' > .babelrc

Put hello.js.

"use strict";

class Hello {
    say(message) {
        console.log(message);
    }
}

new Hello().say("hello");

Transpile hello.js and run it.

$ node_modules/.bin/babel hello.js | node
hello