Skip to content

Instantly share code, notes, and snippets.

@morrow
Created September 6, 2018 20:04
Show Gist options
  • Select an option

  • Save morrow/820b3549ac8f0b726387dab684900049 to your computer and use it in GitHub Desktop.

Select an option

Save morrow/820b3549ac8f0b726387dab684900049 to your computer and use it in GitHub Desktop.
package main
import (
"os"
"fmt"
"net/http"
"io/ioutil"
"log"
"time"
)
func api(term string, latitude string, longitude string) string {
// set up api and request vars
api_url := "https://api.yelp.com/v3/businesses/search"
req, _ := http.NewRequest("GET", api_url, nil)
// add and encode terms, latitude, longitude to send to yelp API server
values := req.URL.Query()
values.Add("term", term)
values.Add("latitude", latitude)
values.Add("longitude", longitude)
req.URL.RawQuery = values.Encode()
// get bearer token from ENV
bearer := os.Getenv("YELP_BEARER_TOKEN")
// add bearer token and disable caching for request
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", bearer))
req.Header.Add("Cache-Control", "no-cache")
// send request, wait for response and process
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)
// return processed response
return string(body)
}
func main() {
// set up web server listening to requests at /
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// print timestamp ip and path for simple logging
fmt.Printf("%v %v %v \n", time.Now().Unix(), r.Header.Get("X-Forwarded-For"), r.URL.Path)
// set HTTP headers for response
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Access-Control-Allow-Origin", "*")
// print response
fmt.Fprintf(w, api(r.URL.Query()["term"][0], r.URL.Query()["latitude"][0], r.URL.Query()["longitude"][0]))
})
// run server and log responses
log.Fatal(http.ListenAndServe(":8080", nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment