Created
October 20, 2014 17:12
-
-
Save dyerw/ab95885a9c6f1bab711c to your computer and use it in GitHub Desktop.
Basic REST Api in Go w/ Gorilla
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 ( | |
"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