Skip to content

Commit

Permalink
Creating API
Browse files Browse the repository at this point in the history
  • Loading branch information
robertoduessmann committed Jul 26, 2017
0 parents commit 8cb0baf
Show file tree
Hide file tree
Showing 4 changed files with 110 additions and 0 deletions.
25 changes: 25 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# weather-api

An REST API to check the current weather.

## Build
```sh
go build
```
## Run
```sh
./weather-api
```
## Usage
```sh
curl http://localhost:3000/weather/{city}
```
## Example
#### Request
```sh
curl http://localhost:3000/weather/Curitiba
```
#### Response
```sh
{"temperature":"17","wind":"4"}
```
59 changes: 59 additions & 0 deletions controller/weather.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package controller

import (
"encoding/json"
"fmt"
"log"
"net/http"

"github.com/PuerkitoBio/goquery"
"github.com/gorilla/mux"
"github.com/robertoduessmann/weather-api/model"
)

func CurrentWeather(w http.ResponseWriter, r *http.Request) {

var weather model.Weather

resp := getExternalWeather(getCity(r))
defer resp.Body.Close()

if resp.StatusCode == 200 {
parse(resp, &weather)
}

fmt.Fprintf(w, string(toJSON(weather)))
}

func getCity(r *http.Request) string {
return mux.Vars(r)["city"]
}

func getExternalWeather(city string) *http.Response {
resp, err := http.Get("http://wttr.in/" + city)
if err != nil {
log.Fatal("Cannot open url: ", err)
}
return resp
}

func parse(resp *http.Response, weather *model.Weather) {
doc, err := goquery.NewDocumentFromReader(resp.Body)
if err != nil {
log.Fatal(err)
}
doc.Find("body > pre > span:nth-child(3)").Each(func(i int, s *goquery.Selection) {
weather.Temperature = s.Text()
})
doc.Find("body > pre > span:nth-child(6)").Each(func(i int, s *goquery.Selection) {
weather.Wind = s.Text()
})
}

func toJSON(weather model.Weather) []byte {
respose, err := json.Marshal(weather)
if err != nil {
fmt.Println(err)
}
return respose
}
20 changes: 20 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package main

import (
"log"
"net/http"

"github.com/gorilla/mux"
"github.com/robertoduessmann/weather-api/controller"
)

func main() {

weather := mux.NewRouter()
weather.Path("/weather/{city}").Methods(http.MethodGet).HandlerFunc(controller.CurrentWeather)

if err := http.ListenAndServe(":3000", weather); err != nil {
log.Fatal(err)
}

}
6 changes: 6 additions & 0 deletions model/weather.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package model

type Weather struct {
Temperature string `json:"temperature"`
Wind string `json:"wind"`
}

0 comments on commit 8cb0baf

Please sign in to comment.