Skip to content

Instantly share code, notes, and snippets.

@robinmonjo
Created June 29, 2013 22:13
Show Gist options
  • Save robinmonjo/5892893 to your computer and use it in GitHub Desktop.
Save robinmonjo/5892893 to your computer and use it in GitHub Desktop.
Simple http server skeleton in Go
package main
import (
"fmt"
"net/http"
"os"
"io/ioutil"
)
func main() {
http.HandleFunc("/", root)
port := os.Getenv("PORT")
if len(port) == 0 {
port = "9999"
}
fmt.Println("listening on port: ", port)
err := http.ListenAndServe(":" + port, nil)
if err != nil {
panic(err)
}
}
//routes
func root(res http.ResponseWriter, req *http.Request) {
body, err := ioutil.ReadAll(req.Body)
if err != nil {
fmt.Fprintf(res, "[ERROR] parsing body : %s", err)
return
}
response := "Remote: "
switch req.Method {
case "GET":
response = response + "getting a GET request with body: " + string(body)
case "POST":
response = response + "getting a POST request with body: " + string(body)
case "PUT":
response = response + "getting a PUT request with body: " + string(body)
case "DEL":
response = response + "getting a DEL request with body: " + string(body)
default:
response = response + "getting an unknown request"
}
fmt.Fprintf(res, response)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment