How to run simple http server in Go

Issue #220

Handle url parameter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package main

import (
"net/http"
"log"
)

func handleGreeting(w http.ResponseWriter, r *http.Request) {
messages, ok := r.URL.Query()["message"]

if !ok || len(messages[0]) < 1 {
log.Println("Message is missing")
w.WriteHeader(400)
return
}

message := messages[0]
w.Write([]byte(message))
}

func main() {
http.HandleFunc("/greet", handleGreeting)
if err := http.ListenAndServe(":8080", nil); err != nil {
panic(err)
}
}

Handle body

1
2
3
4
5
6
7
8
9
10
11
12
type MyRequest struct {
Message string `json:"message"`
}

decoder := json.NewDecoder(r.Body)
var t EphemeralKeysRequest
err := decoder.Decode(&t)
if err != nil {
panic(err)
}

message := t.Message

How to parse json in Go

Issue #199

Unmarshal using encoding/json

  • property in struct needs to be first letter capitalized
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import (
"net/http"
"encoding/json"
"io/ioutil"
"fmt"
)

type MyJsonObject struct {
Id string `json:"id"`
Name string `json:"name"`
}

type MyJsonArray struct {
Data []MyJsonObject `json:"data"`
}

func FetchJson() {
url := "https://myapp.com/json"
client := http.Client{
Timeout: time.Second * 10
}

request, requestError := http.NewRequest(http.MethodGet, url, nil)
request.Header.Set("User-Agent", "myapp")
response, responseError := client.Do(request)
body, readError := ioutil.ReadAll(response.Body)

fmt.Println(requestError, responseError, readError)

myJsonArray := MyJsonArray{}
marshalError := json.Unmarshal(body, &myJsonArray)
fmt.Println(jsonResponse, marshalError)
}

Map

And how to map to another struct
https://gobyexample.com/collection-functions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
func Map(vs []JsonStop, f func(JsonStop) *api.Stop) []*api.Stop {
vsm := make([]*api.Stop, len(vs))
for i, v := range vs {
vsm[i] = f(v)
}
return vsm
}

stops := Map(jsonResponse.Data, func(jsonStop JsonStop) *api.Stop {
stop := api.Stop{
Id: jsonStop.Id,
Name: jsonStop.Name,
Address: jsonStop.Address,
Lat: jsonStop.Lat,
Long: jsonStop.Long}

return &stop
})

json to protobuf