Created
May 27, 2020 06:34
-
-
Save kayslay/4d300833320f40f8c8e387274cb26e25 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 main | |
import ( | |
"encoding/json" | |
"errors" | |
"log" | |
"net/http" | |
) | |
// mockInfoSaver mock implementation of infoSaver | |
type mockInfoSaver struct { | |
} | |
func (b mockInfoSaver) CreateInfo(i *infoModel) error { | |
log.Println("saving to db", i) | |
return nil | |
} | |
var ( | |
ErrNotFound = errors.New("Not Found") | |
defaultInfoBatchRequester = &infoBatchRequester{ | |
pending: map[string][]chan<- infoChan{}, | |
infoSaver: mockInfoSaver{}, | |
} | |
) | |
// getInfo acts like a failed db get operation | |
func getInfo(infoID string) (infoModel, error) { | |
return infoModel{}, errors.New("info does not exists") | |
} | |
// handleSlowThirdParty http handler that makes the call to the third party api | |
func handleSlowThirdParty(w http.ResponseWriter, r *http.Request) { | |
infoID := r.URL.Query().Get("info_id") | |
// make a fake request to get the info | |
info, err := getInfo(infoID) | |
if err != nil { | |
// make a request to get the info | |
result := make(chan infoChan, 1) | |
go defaultInfoBatchRequester.Request(infoID, result) | |
select { | |
//the request was canceled early | |
case <-r.Context().Done(): | |
log.Println("request terminated") | |
//result returned | |
case rs := <-result: | |
if rs.err != nil { | |
http.Error(w, rs.err.Error(), http.StatusBadRequest) | |
} | |
info = rs.info | |
} | |
} | |
b, err := json.Marshal(info) | |
w.Write(b) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment