Objective
Build a web API by using Go language on Linux
Setup Go
-
Download
wget https://dl.google.com/go/go1.12.4.linux-amd64.tar.gz tar -C /usr/local -xzf ./go1.12.4.linux-amd64.tar.gz
-
Configure PATH
Add Go to PATH in ~/.bash_profile
export PATH=$PATH:/usr/local/go/bin
-
Source
. ~/.bash_profile
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!