Rules of Thumb:

  • Are people and their "requirements" going to ruin your day? Use PHP
  • Are computers going to ruin your day? Use Go
package main
import (
"encoding/json"
"fmt"
"net/http"
)
func main() {
  http.HandleFunc("/", func(w http.ResponseWriter,r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    json, _ := json.Marshal(map[string]string{
      "Hello": "World",
    })
    fmt.Fprint(w, string(json))
  })
  http.ListenAndServe(":8080", nil)
}
package main
 
import (
"fmt"
"log"
"net/http"
"encoding/json"
"html/template"
"time"
)
 
func main() {
  http.HandleFunc("/hello", handleHello)
  fmt.Println("serving on http://localhost:7777/hello")
  log.Fatal(http.ListenAndServe("localhost:7777", nil))
}
 
func handleHello(w http.ResponseWriter, req *http.Request) {
    query := req.FormValue("q") // POST parameter
    log.Println("serving", req.URL)
    fmt.Fprintln(w, "Hello, Go!")
}

Martini app

cd ~/go/src
mkdir hello
nano hello/hello.go
package main
import "github.com/codegangsta/martini"
func main() {
    server := martini.Classic()
    server.Get("/", func() string {
        return "<h1>Hello, world!</h1>"
    })
    server.Get("/:param", func(args martini.Params) string {
        return "<h1>Hello " + args["param"] + "</h1>"
    })
    server.Run()
}

Edit the default Nginx configuration file:

sudo nano /etc/nginx/sites-enabled/default
# edit with the correct IP:
server_name your_ip_or_domain;

configure nginx to pass requests to the martini application

location / {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_set_header Host $host;
    proxy_pass http://127.0.0.1:3000;
}

reload:

sudo service nginx restart

un client per un webservice

func main() {
  client := &http.Client{}
  uri := "http://api.service.com/"
  data := url.Values{"foo": {"bar"}}
  // POST request
  r, _ := http.NewRequest("POST", uri,  bytes.NewBufferString(data.Encode()))
  attempts, maxAttempts := 0, 5
  var (
    resp *http.Response
    err error
  )
  retries := 5
  for i := 0; i < retries; i++ {
    resp, err = client.Do(r)
    netErr, conversionOK := err.(net.Error)
    if err == nil || conversionOK && netErr.Temporary() {
      break
    }
    time.Sleep(3)
  }
  if err != nil {
    panic(err)
  }
  // do something with resp here
}