country.go 788 Bytes
Newer Older
1
2
3
4
5
6
package handler

import (
	"assignment-1/pkg"
	"encoding/json"
	"github.com/gorilla/mux"
7
	"log"
8
9
10
	"net/http"
)

11
// handles requests for /country/
12
13
func Chandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
Aksel Baardsen's avatar
Aksel Baardsen committed
14
	limit := r.FormValue("limit") // gets the limit, if specified in url
15
16

	// unnecessary default limit (gbif API has default of 20)
17
18
19
20
	if len(limit) == 0 {
		limit = "5"
	}

21
	// gets a country-struct containing data, or error
22
	country, err := pkg.GetCountryByCode(vars["country_identifier"], limit)
23

24
	if err == nil {
25
		w.Header().Set("Content-Type", "application/json")
26
		err = json.NewEncoder(w).Encode(&country)
27
28
29
		if err != nil {
			log.Fatal(err)
		}
Aksel Baardsen's avatar
Aksel Baardsen committed
30
	} else {
31
		// need to check error for content when setting header (pkg.CorrectHeader)
32
		pkg.HttpError(w, err)
Aksel Baardsen's avatar
Aksel Baardsen committed
33
	}
34
}