func auth(w http.ResponseWriter, r *http.Request) { username, password, ok := r.BasicAuth() if !ok { response.Forbidden(w) return } instapaperClient := instapaper.New(username, password) ok, err := instapaperClient.Authenticate() if err != nil { response.InternalServerError(w) return } if ok { response.OK(w) return } response.Forbidden(w) }
func importStories(w http.ResponseWriter, r *http.Request) { if r.Method != "POST" { log.Printf("%v method not allowed for /import", r.Method) response.MethodNotAllowed(w) return } username, password, ok := r.BasicAuth() if !ok { response.Forbidden(w) return } limit := parseLimit(r) log.Printf("importing %v stories for %v", limit, username) hnClient := hn.New() stories, err := hnClient.TopStories() if err != nil { response.BadGateway(w, err) return } var errs []error var addedStories []hn.Item instapaperClient := instapaper.New(username, password) s := semaphore.New(10) var wg sync.WaitGroup for i, id := range stories { if i >= limit { break } wg.Add(1) s.Acquire(1) go func(id int) { defer wg.Done() defer s.Release(1) story, err := hnClient.GetPost(id) if err != nil { errs = append(errs, err) return } if story.URL == nil { log.Printf("skipping story %v with title %v", id, story.Title) return } _, err = instapaperClient.Add(instapaper.AddParams{ URL: *story.URL, Title: story.Title, }) if err != nil { errs = append(errs, err) log.Println("error adding", story, err) return } addedStories = append(addedStories, story) }(id) } wg.Wait() if len(errs) != 0 { response.BadGateway(w, errs, addedStories) return } log.Printf("imported %v stories for %v", len(addedStories), username) response.JSON(w, addedStories) }