Network Programming with Go
Concepts of Programming Languages
Sebastian Macke
Rosenheim Technical University
Sebastian Macke
Rosenheim Technical University
Blog article
Don't Crack Under Pressure: Java Microservices and the Battle for Stability Under High Load
4History:
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> ....
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
Truly portable data.
All can be transported via HTTP.
{ "coord": { "lon": -122.08, "lat": 37.39 }, "weather": [ { "main": "Clear", "description": "clear sky", } ], }
Types:
- bool
- floating point number
- strings
- arrays
- null
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)) }
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) }
Call the Github API with Go to receive the repositories with the most stars and the query "awesome"
api.github.com/search/repositories?sort=stars&order=desc&q=awesome
to instantly create a Go structure from an arbitrary JSON.
17func 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
@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!"; } }