Get Adobe Flash player

go

So I wanted to test a Go Web running on Cloud Foundry and I’m still homing my skills in this area. I needed a simple hello world web app and found some Go examples on the web that use the net/http package.

 

package main

import (

“fmt”

“net/http”

)

func handler(w http.ResponseWriter, r *http.Request) {

fmt.Fprintf(w, “Hi there, this is a Go App running on CF %s!”, r.URL.Path[1:])

}

func main() {

http.HandleFunc(“/”, handler)

http.ListenAndServe(“:8080”, nil)

}


I ran into an issue which was a school boy error and fundamental to Cloud Foundry. If you view the above code you will notice I hard coded the http listeners to port 8080. WaWARRR.. The mistake was presuming I could get a route bag to my CF container from the outside world on a specific port number.

 

CF will give each instance of your app container a dynamical port number. The key in your code to make use of an environment variable called “PORT”. To do that you need to first import the “os” package so you can make use of the “Getenv” function to retrieve the value of the assigned port. Now my code looks like this:

 

package main

import (

“fmt”

“net/http”

“os”

)

func handler(w http.ResponseWriter, r *http.Request) {

fmt.Fprintf(w, “Hi there Ricky, this is a Go App running on CF %s!”, r.URL.Path[1:])

}

func main() {

http.HandleFunc(“/”, handler)

http.ListenAndServe(“:”+os.Getenv(“PORT”), nil)

}

 

 

Now when you access your application through cloud foundry, CF will route you through to the correct port.

Banner Adverts