Network Programming with Go

Concepts of Programming Languages

Sebastian Macke

Rosenheim Technical University

Last lecture

2

About this Lecture

3

What makes networking a programming concept?

Blog article

4

The Internet protocol stack

5

HTTP

6

Hypertext Transfer Protocol

History:

7

Example communication

Client sends the request to GET the content of the root path "/index.html"

GET /index.html HTTP/1.1
Host: www.example.com

Server responds via

HTTP/1.1 200 OK
Date: Mon, 23 May 2021 16:14:34 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 155
Server: Apache

<html>
....
8

A Simple HTTP File Server

func main() {
    port := flag.String("p", "8081", "port to serve on")
    directory := flag.String("d", ".", "the directory of static file to host")
    flag.Parse()

    dirFs := os.DirFS(*directory)
    http.Handle("/", http.FileServer(http.FS(dirFs)))
    fmt.Printf("Starting server at port " + *port + "\n")
    log.Fatal(http.ListenAndServe(":"+*port, nil))
}

Python equivalent is still simpler

python -m http.server 8080
9

Transfer formats

10

There are different types of standardized transfer formats

Truly portable data.
All can be transported via HTTP.

11

JSON - JavaScript Object Notation

{
    "coord": {
        "lon": -122.08,
        "lat": 37.39
      },
      "weather": [
          {
              "main": "Clear",
              "description": "clear sky",
          }
      ],
}

Types:
- bool
- floating point number
- strings
- arrays
- null

12

Marshalling and Unmarshalling

type Weather struct {
    City        string `json:"city"` // The tag defines the exact name in the json.
    Sky         string `json:"sky"`
    Temperature int    `json:"temp"`
}

func main() {
    var weather Weather
    // Tags are accessible via reflection
    fmt.Println("Tag of first field entry", reflect.TypeOf(weather).Field(0).Tag)

    weatherJson := `{"city": "Rosenheim","sky": "clear", "temp": 15}`
    err := json.Unmarshal([]byte(weatherJson), &weather)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("City: %s\nSky: %s\nTemperature: %d\n", weather.City, weather.Sky, weather.Temperature)
    s, _ := json.Marshal(weather)
    fmt.Println(string(s))
}
13

REST is a paradigm for application services

14

REST APIs with Go

15

Example: Weather API with Go: Short version

func main() {
    response, err := http.Get("http://wttr.in/Rosenheim?format=j1")
    if err != nil {
        panic(err)
    }
    var forecast WeatherForecast
    err = json.NewDecoder(response.Body).Decode(&forecast)
    if err != nil {
        panic(err)
    }
    fmt.Printf("Temperature in Rosenheim: %s°C\n", forecast.CurrentCondition[0].TempC)
}
16

Exercise

Call the Github API with Go to receive the repositories with the most stars and the query "awesome"

to instantly create a Go structure from an arbitrary JSON.

17

REST API with Go

func HandleNotFound(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusNotFound)
    fmt.Fprintf(w, "Nothing to see here\n")
}

func EchoParameters(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    data, _ := json.Marshal(r.URL.Query())
    w.Write(data)
}

func main() {
    http.HandleFunc("/", HandleNotFound)
    http.HandleFunc("/api/echoParams", EchoParameters)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

Each request is processed in its separate go routine.

To test the rest interface you can use tools such as
- curl, httpie, Postman, Your own Go Rest call code, Web Browser

18

Comparison with Java (Spring Boot)

@SpringBootApplication
@RestController
public class RestdemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(RestdemoApplication.class, args);
    }

    @GetMapping("/")
    public String index() {
        return "Greetings from Spring Boot!";
    }
}
19

Thank you

Sebastian Macke

Rosenheim Technical University

Use the left and right arrow keys or click the left and right edges of the page to navigate between slides.
(Press 'H' or navigate to hide this message.)