Go - Build a web API

Bruce Lu

July 4, 2019

Objective

Build a web API by using Go language on Linux

Setup Go

Create a Go project

mkdir -p /opt/ws/go/src/blue/http
cd /opt/ws/go/src/blue/http
vim BlueHTTPServer.go
package main;

import (
  "net/http"
)

func say(res http.ResponseWriter, req *http.Request) {
  res.Write([]byte("Hey Bruce!"));
}

func main(){
  http.HandleFunc("/say", say);
  http.Handle("/say2", http.HandlerFunc(say));
  http.ListenAndServe(":10001", nil);
  select{};
}

Build and run

go build BlueHTTPServer.go
./BlueHTTPServer

Test

curl http://localhost:10001/say
curl http://localhost:10001/say2

# I can see output like this: Hey Bruce!