Skip to content

Instantly share code, notes, and snippets.

@nono
Created April 7, 2012 21:14
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nono/2332143 to your computer and use it in GitHub Desktop.
Save nono/2332143 to your computer and use it in GitHub Desktop.
A HTTP version of Hello world in Go
package main
import (
"encoding/json"
"flag"
"github.com/bmizerany/pat"
"io"
"log"
"net/http"
)
type Response struct {
Hello string
}
func HelloWorld(w http.ResponseWriter, req *http.Request) {
var response Response
response.Hello = req.URL.Query().Get(":name")
b, err := json.Marshal(response)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
io.WriteString(w, string(b))
}
func main() {
var addr string
flag.StringVar(&addr, "addr", "127.0.0.1:8000", "Bind to this address:port")
flag.Parse()
m := pat.New()
m.Get("/hello/:name", http.HandlerFunc(HelloWorld))
http.Handle("/", m)
err := http.ListenAndServe(addr, nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment