-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #33 from vosmith/multipart
initial work on multipart requests, issue #8
- Loading branch information
Showing
3 changed files
with
134 additions
and
8 deletions.
There are no files selected for viewing
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
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
package main | ||
|
||
import ( | ||
"fmt" | ||
"io/ioutil" | ||
"net/http" | ||
"os" | ||
"time" | ||
|
||
"github.com/asciimoo/colly" | ||
) | ||
|
||
func generateFormData() map[string][]byte { | ||
f, _ := os.Open("asciimoo.jpg") | ||
defer f.Close() | ||
|
||
imgData, _ := ioutil.ReadAll(f) | ||
|
||
return map[string][]byte{ | ||
"firstname": []byte("one"), | ||
"lastname": []byte("two"), | ||
"email": []byte("onetwo@example.com"), | ||
"file": imgData, | ||
} | ||
} | ||
|
||
func setupServer() { | ||
var handler http.HandlerFunc = func(w http.ResponseWriter, r *http.Request) { | ||
fmt.Println("received request") | ||
err := r.ParseMultipartForm(10000000) | ||
if err != nil { | ||
fmt.Println("server: Error") | ||
w.WriteHeader(500) | ||
w.Write([]byte("<html><body>Internal Server Error</body></html>")) | ||
return | ||
} | ||
w.WriteHeader(200) | ||
fmt.Println("server: OK") | ||
w.Write([]byte("<html><body>Success</body></html>")) | ||
} | ||
|
||
go http.ListenAndServe(":8080", handler) | ||
} | ||
|
||
func main() { | ||
// Start a single route http server to post an image to. | ||
setupServer() | ||
|
||
c := colly.NewCollector() | ||
c.AllowURLRevisit = true | ||
c.MaxDepth = 5 | ||
|
||
// On every a element which has href attribute call callback | ||
c.OnHTML("html", func(e *colly.HTMLElement) { | ||
fmt.Println(e.Text) | ||
time.Sleep(1 * time.Second) | ||
e.Request.PostMultipart("http://localhost:8080/", generateFormData()) | ||
}) | ||
|
||
// Before making a request print "Visiting ..." | ||
c.OnRequest(func(r *colly.Request) { | ||
fmt.Println("Posting asciimoo.jpg to", r.URL.String()) | ||
}) | ||
|
||
// Start scraping | ||
c.PostMultipart("http://localhost:8080/", generateFormData()) | ||
c.Wait() | ||
} |