Created
November 4, 2020 08:55
-
-
Save harshitsinghai77/5f38af71c168b476b49ffb28090534f3 to your computer and use it in GitHub Desktop.
using go-restful to create REST API using go programming language.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"database/sql" | |
"encoding/json" | |
"log" | |
"net/http" | |
"time" | |
"github.com/emicklei/go-restful" | |
"github.com/harshitsinghai/dbutils" | |
_ "github.com/mattn/go-sqlite3" | |
) | |
// DB Driver visible to whole program | |
var DB *sql.DB | |
// ClubResource is the model for holding club information | |
type ClubResource struct { | |
ID int | |
NAME string | |
COUNTRY string | |
STADIUM string | |
CreatedAt string | |
} | |
// PlayerResource is the model for holding player information | |
type PlayerResource struct { | |
ID int | |
NAME string | |
ClubID int | |
AGE int | |
POSITION string | |
CreatedAt string | |
} | |
// Register ClubResource add paths and routes to container | |
func (c *ClubResource) Register(container *restful.Container) { | |
ws := new(restful.WebService) | |
ws.Path("/club").Consumes(restful.MIME_JSON).Produces(restful.MIME_JSON) | |
ws.Route(ws.GET("").To(c.getAllClub)) | |
ws.Route(ws.GET("/{club-id}").To(c.getClub)) | |
ws.Route(ws.POST("").To(c.createClub)) | |
ws.Route(ws.DELETE("/{club-id}").To(c.removeClub)) | |
container.Add(ws) | |
} | |
// Register PlayerResource add paths and routes to container | |
func (p *PlayerResource) Register(container *restful.Container) { | |
ws := new(restful.WebService) | |
ws.Path("/player").Consumes(restful.MIME_JSON).Produces(restful.MIME_JSON) | |
ws.Route(ws.GET("").To(p.getAllPlayer)) | |
ws.Route(ws.GET("/{player-id}").To(p.getPlayer)) | |
ws.Route(ws.POST("").To(p.createPlayer)) | |
ws.Route(ws.DELETE("/{player-id}").To(p.removePlayer)) | |
container.Add(ws) | |
} | |
// GET http://localhost:8000/club | |
func (c ClubResource) getAllClub(request *restful.Request, response *restful.Response) { | |
rows, err := DB.Query("SELECT ID, NAME, COUNTRY, STADIUM, CreatedAt from clubs LIMIT 20") | |
var tempClub ClubResource | |
var allClub = []ClubResource{} | |
if err != nil { | |
response.AddHeader("Content-Type", "text/plain") | |
response.WriteErrorString(http.StatusNotFound, "Clubs could not be found.") | |
return | |
} | |
for rows.Next() { | |
rows.Scan(&tempClub.ID, &tempClub.NAME, &tempClub.COUNTRY, &tempClub.STADIUM, &tempClub.CreatedAt) | |
allClub = append(allClub, tempClub) | |
} | |
response.WriteEntity(allClub) | |
} | |
// GET http://localhost:8000/club/1 | |
func (c ClubResource) getClub(request *restful.Request, response *restful.Response) { | |
id := request.PathParameter("club-id") | |
var tempPlayer PlayerResource | |
var clubDetails struct { | |
CLUB ClubResource | |
PLAYERS []PlayerResource | |
} | |
cluberr := DB.QueryRow("SELECT * from clubs WHERE ID = ?", id).Scan(&clubDetails.CLUB.ID, &clubDetails.CLUB.NAME, &clubDetails.CLUB.COUNTRY, &clubDetails.CLUB.STADIUM, &clubDetails.CLUB.CreatedAt) | |
rows, err := DB.Query("SELECT players.ID, players.NAME, players.POSITION, players.AGE, players.ClubID from clubs INNER JOIN players ON clubs.ID == players.ClubID WHERE clubs.ID = ?", id) | |
if err != nil && cluberr != nil { | |
log.Println(err) | |
response.AddHeader("Content-Type", "text/plain") | |
response.WriteErrorString(http.StatusNotFound, "Trains could not be found.") | |
return | |
} | |
for rows.Next() { | |
rows.Scan(&tempPlayer.ID, &tempPlayer.NAME, &tempPlayer.POSITION, &tempPlayer.AGE, &tempPlayer.ClubID) | |
clubDetails.PLAYERS = append(clubDetails.PLAYERS, tempPlayer) | |
} | |
response.WriteEntity(clubDetails) | |
} | |
// POST http://localhost:8000/club | |
func (c ClubResource) createClub(request *restful.Request, response *restful.Response) { | |
decoder := json.NewDecoder(request.Request.Body) | |
var tempClub ClubResource | |
err := decoder.Decode(&tempClub) | |
statement, _ := DB.Prepare(`INSERT INTO clubs | |
(NAME, COUNTRY, STADIUM, CreatedAt) VALUES (?, ?, ?, ?)`) | |
result, err := statement.Exec(tempClub.NAME, tempClub.COUNTRY, tempClub.STADIUM, time.Now()) | |
if err == nil { | |
newID, _ := result.LastInsertId() | |
tempClub.ID = int(newID) | |
response.WriteHeaderAndEntity(http.StatusCreated, tempClub) | |
} else { | |
response.AddHeader("Content-Type", "text/plain") | |
response.WriteErrorString(http.StatusInternalServerError, err.Error()) | |
} | |
} | |
// DELETE http://localhost:8000/club/1 | |
func (c ClubResource) removeClub(request *restful.Request, response *restful.Response) { | |
id := request.PathParameter("club-id") | |
statement, _ := DB.Prepare("DELETE FROM clubs WHERE ID=?") | |
_, err := statement.Exec(id) | |
if err == nil { | |
response.WriteHeader(http.StatusOK) | |
} else { | |
response.AddHeader("Content-Type", "text/plain") | |
response.WriteErrorString(http.StatusInternalServerError, err.Error()) | |
} | |
} | |
// GET http://localhost:8000/player | |
func (p PlayerResource) getAllPlayer(request *restful.Request, response *restful.Response) { | |
rows, err := DB.Query("SELECT ID, NAME, ClubID, AGE, POSITION, CreatedAt from players LIMIT 20") | |
var tempPlayer PlayerResource | |
var allPlayer = []PlayerResource{} | |
if err != nil { | |
response.AddHeader("Content-Type", "text/plain") | |
response.WriteErrorString(http.StatusNotFound, "Clubs could not be found.") | |
} | |
for rows.Next() { | |
rows.Scan(&tempPlayer.ID, &tempPlayer.NAME, &tempPlayer.ClubID, &tempPlayer.AGE, &tempPlayer.POSITION, &tempPlayer.CreatedAt) | |
allPlayer = append(allPlayer, tempPlayer) | |
} | |
response.WriteEntity(allPlayer) | |
} | |
// GET http://localhost:8000/player/1 | |
func (p PlayerResource) getPlayer(request *restful.Request, response *restful.Response) { | |
id := request.PathParameter("player-id") | |
err := DB.QueryRow("SELECT ID, NAME, ClubID, AGE, POSITION from players WHERE ID=?", id).Scan(&p.ID, &p.NAME, &p.ClubID, &p.AGE, &p.POSITION) | |
if err != nil { | |
log.Println(err) | |
response.AddHeader("Content-Type", "text/plain") | |
response.WriteErrorString(http.StatusNotFound, "Player could not be found.") | |
} else { | |
response.WriteEntity(p) | |
} | |
} | |
// POST http://localhost:8000/player | |
func (p PlayerResource) createPlayer(request *restful.Request, response *restful.Response) { | |
decoder := json.NewDecoder(request.Request.Body) | |
var tempPlayer PlayerResource | |
err := decoder.Decode(&tempPlayer) | |
if err != nil { | |
response.AddHeader("Content-Type", "text/plain") | |
response.WriteErrorString(http.StatusInternalServerError, | |
err.Error()) | |
} | |
statement, _ := DB.Prepare("INSERT INTO players (NAME, ClubID, AGE, POSITION, CreatedAt) VALUES (?, ?, ?, ?, ?)") | |
result, err := statement.Exec(tempPlayer.NAME, tempPlayer.ClubID, tempPlayer.AGE, tempPlayer.POSITION, time.Now()) | |
if err == nil { | |
newID, _ := result.LastInsertId() | |
tempPlayer.ID = int(newID) | |
response.WriteHeaderAndEntity(http.StatusCreated, tempPlayer) | |
} else { | |
response.AddHeader("Content-Type", "text/plain") | |
response.WriteErrorString(http.StatusInternalServerError, err.Error()) | |
} | |
} | |
// DELETE http://localhost:8000/club/1 | |
func (p PlayerResource) removePlayer(request *restful.Request, response *restful.Response) { | |
id := request.PathParameter("player-id") | |
statement, _ := DB.Prepare("DELETE FROM players WHERE ID=?") | |
_, err := statement.Exec(id) | |
if err == nil { | |
response.WriteHeader(http.StatusOK) | |
} else { | |
response.AddHeader("Content-Type", "text/plain") | |
response.WriteErrorString(http.StatusInternalServerError, err.Error()) | |
} | |
} | |
func main() { | |
var err error | |
// Connect to Database | |
DB, err = sql.Open("sqlite3", "./players.db") | |
if err != nil { | |
log.Println("Driver creation failed!") | |
} | |
// Create tables | |
dbutils.Initialize(DB) | |
wsContainer := restful.NewContainer() | |
wsContainer.Router(restful.CurlyRouter{}) | |
c := ClubResource{} | |
c.Register(wsContainer) | |
p := PlayerResource{} | |
p.Register(wsContainer) | |
log.Println("Started listening on PORT 8000") | |
server := &http.Server{ | |
Addr: ":8000", | |
Handler: wsContainer, | |
} | |
log.Fatal(server.ListenAndServe()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment