Skip to content
Snippets Groups Projects
Commit 62390f79 authored by jotangen's avatar jotangen
Browse files

Creating get and parser

parent 9463ff7e
Branches
No related tags found
No related merge requests found
main.go 0 → 100644
package main
import (
"fmt"
"html"
"log"
"net/http"
"os"
)
//Server that prints halli
func helloHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
}
func main() {
port := os.Getenv("PORT")
port = "8080"
if port == "" {
log.Fatal("$PORT must be set")
}
//This is code for tsting receiving get req
//From YT:Simple GET req example
//Get country by name
country := getCountryName()
fmt.Println("Country name is s%",country)
http.HandleFunc("/", helloHandler)
log.Fatal(http.ListenAndServe(":"+port, nil))
}
package main
/*func TestMain(t *testing.T) {
want := "Hello, world."
if got := Hello(); got != want {
t.Errorf("Hello() = %q, want %q", got, want)
}
}
*/
package main
import (
"encoding/json"
"fmt"
"net/http"
)
const apiRoot = "https://restcountries.eu/rest/v2/alpha/"
//We receive JSON code and we parse it
//CntrInfo contains a response for restcountries endpoint
type CntrInfo struct {
CallingCode int32 //"47"
Name string `json:"name"` //"country":"norway"
NameCode string //"NO"
}
//Should return the name Norway
func getCountryName() string {
//Change hardcoded to func parameters "We pass them"
countryCode := "NO"
url := apiRoot + countryCode
//resp is json, so we need to parse it
resp, err := http.Get(url)
if err !=nil {
fmt.Println("Error:we have a problem", err)
return ""
}
//Closes when surrounded functions are finished
defer resp.Body.Close()
//Pointer to struct
ci := &CntrInfo{}
//resp.Body JSON
//NewDecoder returns a new decoder that reads from r
json.NewDecoder(resp.Body).Decode(ci)
return "ci.Name"
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment