Skip to content

Instantly share code, notes, and snippets.

@grantglidewell
Last active December 4, 2018 18:02
Show Gist options
  • Select an option

  • Save grantglidewell/3785fa997098a75fda81483374e0df99 to your computer and use it in GitHub Desktop.

Select an option

Save grantglidewell/3785fa997098a75fda81483374e0df99 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"io/ioutil"
"net/http"
"strconv"
"strings"
"time"
)
func main() {
fmt.Println(scrape("URL", "SearchTerm"))
}
func scrape(u string, t string) (string, error) {
// Make the http request for the resource
resp, err := http.Get(u)
if err != nil {
return "", err
}
// Close the connection when the response is complete
defer resp.Body.Close()
// Read the response body to a variable
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
// Create a unique token for filename
ts := strconv.FormatInt(time.Now().UTC().UnixNano(), 10)
// Generate a string for the filename
filename := fmt.Sprintf("scrape%v.html", ts)
// Write body as a file to disk
ioutil.WriteFile(filename, body, 0644)
// Read the file to a variable
dat, err := ioutil.ReadFile(filename)
if err != nil {
return "", err
}
// Check if the search term is present
if strings.Contains(string(dat), t) {
// Return a message to the user that the search term was found
return fmt.Sprintf("Found %[1]s in %[2]s", t, u), nil
}
// Return a message to the user that the search term was not found
return fmt.Sprintf("%[1]s was not found in %[2]s", t, u), nil
}
@weienwong
Copy link

  1. scrape() should have the following signature func scrape(u string, t string) (string, error)
  2. Remove your check() function. Replace it's invocations with:
if err != nil {
   return "", err
}

It seems repetitive but this is the the "Go way" is to perform error checks.
3. There is no need to create a new error variable. This goes back to point #1. If you ever receive an error in Go, you should return the error so you can discontinue execution. Hence all your variables should be named err. Also for the sake of performance, don't allocate variables unncessarily.
4. When appending strings to each other, you should use fmt.Sprintf or strings.Builder for large string concatenations. For example, replace line 30 with fln := fmt.Sprintf("scrape%v.html", ts).
5. I know Go has variable naming conventions, but something like bdy should be named body, fln be named filename and so forth.
6. Perform a nil check on line 35.

@grantglidewell
Copy link
Author

Thanks, very helpful

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment