Skip to content

Instantly share code, notes, and snippets.

@hadoan
Created June 1, 2020 06:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hadoan/44435f850fabab3960f4a618fdc6f14b to your computer and use it in GitHub Desktop.
Save hadoan/44435f850fabab3960f4a618fdc6f14b to your computer and use it in GitHub Desktop.
func getJobPostsEndpoint(response http.ResponseWriter, request *http.Request) {
response.Header().Add("content-type", "application/json")
var jobs []Job
collection := client.Database("Default").Collection("AppJobs")
ctx, _ := context.WithTimeout(context.Background(), 30*time.Second)
cursor, err := collection.Find(ctx, bson.M{})
if err != nil {
response.WriteHeader(http.StatusInternalServerError)
response.Write([]byte(`{"message": ` + err.Error() + `"}`))
return
}
defer cursor.Close(ctx)
for cursor.Next(ctx) {
var job Job
cursor.Decode(&job)
fmt.Printf("%+v\n", job)
jobs = append(jobs, job)
}
if err := cursor.Err(); err != nil {
response.WriteHeader(http.StatusInternalServerError)
response.Write([]byte(`{"message": ` + err.Error() + `"}`))
return
}
json.NewEncoder(response).Encode(jobs)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment