Created
July 6, 2015 21:59
-
-
Save chadlung/2c3785a28badc2dbf353 to your computer and use it in GitHub Desktop.
Go: Simple, Easy, Fast - Building a Go (golang) REST Service with Gorilla - Step 2: http://www.giantflyingsaucer.com/blog/?p=5635
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" | |
"fmt" | |
"log" | |
"net/http" | |
"github.com/gorilla/mux" | |
) | |
// Movie Struct | |
type Movie struct { | |
Title string `json:"title"` | |
Rating string `json:"rating"` | |
Year string `json:"year"` | |
} | |
func main() { | |
router := mux.NewRouter() | |
router.HandleFunc("/movies", handleMovies).Methods("GET") | |
http.ListenAndServe(":8080", router) | |
} | |
func handleMovies(res http.ResponseWriter, req *http.Request) { | |
res.Header().Set("Content-Type", "application/json") | |
var movies = map[string]*Movie{ | |
"tt0076759": &Movie{Title: "Star Wars: A New Hope", Rating: "8.7", Year: "1977"}, | |
"tt0082971": &Movie{Title: "Indiana Jones: Raiders of the Lost Ark", Rating: "8.6", Year: "1981"}, | |
} | |
outgoingJSON, error := json.Marshal(movies) | |
if error != nil { | |
log.Println(error.Error()) | |
http.Error(res, error.Error(), http.StatusInternalServerError) | |
return | |
} | |
fmt.Fprint(res, string(outgoingJSON)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment