Created
April 7, 2012 21:14
-
-
Save nono/2332143 to your computer and use it in GitHub Desktop.
A HTTP version of Hello world in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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