Skip to content

Instantly share code, notes, and snippets.

@dyerw
Created October 20, 2014 17:12
Show Gist options
  • Save dyerw/ab95885a9c6f1bab711c to your computer and use it in GitHub Desktop.
Save dyerw/ab95885a9c6f1bab711c to your computer and use it in GitHub Desktop.
Basic REST Api in Go w/ Gorilla
package main
import (
"net/http"
"encoding/json"
"github.com/gorilla/mux"
)
func HomeHandler(rw http.ResponseWriter, r *http.Request) {
rw.Header().Set("Content-Type", "application/json")
rw.Write([]byte("home"))
}
func CountryHandler(rw http.ResponseWriter, r *http.Request) {
rw.Header().Set("Content-Type", "application/json")
js, _ := json.Marshal([]string{"bolivia", "russia", "germany", "italy"})
rw.Write(js)
}
func CityHandler(rw http.ResponseWriter, r *http.Request) {
rw.Header().Set("Content-Type", "application/json")
js, _ := json.Marshal([]string{"chicago", "moscow", "munich", "milan"})
rw.Write(js)
}
func main() {
r := mux.NewRouter()
// Map url routes to functions
r.HandleFunc("/", HomeHandler)
r.HandleFunc("/countries", CountryHandler)
r.HandleFunc("/cities", CityHandler)
http.Handle("/", r)
// Start server
http.ListenAndServe(":3000", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment