Last active
November 20, 2019 13:52
-
-
Save ninadingole/b4820ba0f145216ae93dd7b2d5a26955 to your computer and use it in GitHub Desktop.
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 internal | |
import ( | |
"context" | |
"encoding/json" | |
"errors" | |
"fmt" | |
"log" | |
"net/http" | |
"os" | |
"time" | |
"github.com/opencensus-integrations/gomongowrapper" | |
) | |
var ( | |
APIkey = os.Getenv("MOVIES_API_KEY") | |
) | |
func MoviesHandler(client *http.Client, mongodbClient *mongowrapper.WrappedClient) http.HandlerFunc { | |
return func(w http.ResponseWriter, r *http.Request) { | |
ctx := r.Context() | |
movieId := r.URL.Query().Get("id") | |
data, _ := getMovie(ctx, client, movieId) | |
err := saveMovie(ctx, mongodbClient, data) | |
if err != nil { | |
w.WriteHeader(http.StatusInternalServerError) | |
return | |
} | |
w.Write([]byte("Movie Added")) | |
} | |
} | |
func saveMovie(ctx context.Context, client *mongowrapper.WrappedClient, data interface{}) error { | |
timeout, cancelFunc := context.WithTimeout(ctx, 2 * time.Second) | |
defer cancelFunc() | |
if rs, err := client.Database("test").Collection("movies").InsertOne(timeout, data); err == nil { | |
fmt.Printf("Data inserted: %s", rs.InsertedID) | |
return nil | |
} | |
return errors.New("error while inserting data") | |
} | |
func getMovie(ctx context.Context, client *http.Client, movieId string) (interface{}, error) { | |
i := fmt.Sprintf("https://api.themoviedb.org/3/movie/%s?api_key=%s", movieId,APIkey) | |
req, e := http.NewRequest("GET", i, nil) | |
if e != nil { | |
log.Println(e) | |
} | |
req.WithContext(ctx) | |
response, e := client.Do(req) | |
if e == nil && response != nil && response.StatusCode == http.StatusOK { | |
var data map[string]interface{} | |
if e := json.NewDecoder(response.Body).Decode(&data); e != nil { | |
return nil, e | |
} | |
return data, nil | |
} | |
return nil, e | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment