Skip to content

Commit

Permalink
Revert
Browse files Browse the repository at this point in the history
  • Loading branch information
motyar committed Nov 27, 2014
1 parent c128c4b commit f099bb4
Show file tree
Hide file tree
Showing 3 changed files with 122 additions and 177 deletions.
11 changes: 1 addition & 10 deletions README.md
@@ -1,33 +1,24 @@
#REST API in Golang with mySql Database

# Install go lang
# Install mysql

# Installation

git clone https://github.com/motyar/restgomysql
go get github.com/go-sql-driver/mysql
cd restgomysql
go run server.go

And open http://localhost:1234/api or http://<ip>:1234/api

Notes: This requires a valid mysql user account. It also requires a schema. For instance, to use database 'test', create the panda table by running something like this:
- mysql -uuser -p -Dtest < farm.sql
And open http://IP_or_localhost:1234/api

# Nothing but (cute) Pandas

GET /api/ to get all the pandas.
- curl http://localhost:1234/api/

POST /api/ to add new panda {name}
- curl -H "Content-Type: application/json" -X POST -d '{"Name":"new panda"}' http://localhost:1234/api/

DELETE /api/panda_id to remove that one panda.
- curl -XDELETE "http://localhost:1234/api/18"

PUT /api/ to update details {id and name}
- curl -H "Content-Type: application/json" -X PUT -d '{"Id":1,"Name":"panda1"}' http://localhost:1234/api/



37 changes: 0 additions & 37 deletions farm.sql

This file was deleted.

251 changes: 121 additions & 130 deletions server.go
Expand Up @@ -5,171 +5,162 @@
// Usage:
//
// # run go server in the background
// $ go run server.go
// $ go run server.go

package main

import (
"database/sql"
"encoding/json"
"flag"
"fmt"
_ "github.com/go-sql-driver/mysql"
"io/ioutil"
"io/ioutil"
"strconv"
"log"
"strings"
"net/http"
"strconv"
"strings"
"encoding/json"
"database/sql"
_ "github.com/go-sql-driver/mysql"
)

var apiport *int = flag.Int("apiport", 1234, "The port to listen on for the api.")
var dbhost = flag.String("dbhost", "localhost", "The mysql hostname/ip address.")
var dbport *int = flag.Int("dbport", 3306, "The mysql port number.")
var dbuser = flag.String("dbuser", "root", "The mysql username to use to access the database.")
var dbpass = flag.String("dbpass", "", "The mysql password to use to access the database.")
var dbname = flag.String("dbname", "test", "The mysql database name.")
var debug *bool = flag.Bool("debug", false, "Print extra debugging info.")

type Panda struct {
Id int
Name string

type Panda struct {
Id int
Name string
}

//Handle all requests
func Handler(response http.ResponseWriter, request *http.Request) {
response.Header().Set("Content-type", "text/html")
webpage, err := ioutil.ReadFile("index.html")
if err != nil {
http.Error(response, fmt.Sprintf("home.html file error %v", err), 500)
}
fmt.Fprint(response, string(webpage))
func Handler(response http.ResponseWriter, request *http.Request){
response.Header().Set("Content-type", "text/html")
webpage, err := ioutil.ReadFile("index.html")
if err != nil {
http.Error(response, fmt.Sprintf("home.html file error %v", err), 500)
}
fmt.Fprint(response, string(webpage));
}

// Respond to URLs of the form /generic/...
func APIHandler(response http.ResponseWriter, request *http.Request) {
func APIHandler(response http.ResponseWriter, request *http.Request){

//Connect to database
connectString := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", *dbuser, *dbpass, *dbhost, *dbport, *dbname)
if *debug {
fmt.Printf("connectString:%s\n", connectString)
}
db, e := sql.Open("mysql", connectString)
if e != nil {
fmt.Print(e)
}
//Connect to database
db, e := sql.Open("mysql", "username:password@tcp(localhost:3306)/farm")
if( e != nil){
fmt.Print(e)
}

//set mime type to JSON
response.Header().Set("Content-type", "application/json")
//set mime type to JSON
response.Header().Set("Content-type", "application/json")


err := request.ParseForm()
if err != nil {
http.Error(response, fmt.Sprintf("error parsing url %v", err), 500)
}

result := []string{}

switch request.Method {
case "GET":
st, err := db.Prepare("select * from pandas limit 10")
if err != nil {
fmt.Print(err)
}
rows, err := st.Query()
if err != nil {
fmt.Print(err)
}
for rows.Next() {
var name string
var id int
err = rows.Scan(&id, &name)
panda := &Panda{Id: id, Name: name}
b, err := json.Marshal(panda)
if err != nil {
fmt.Println(err)
return
}
tmpString := fmt.Sprintf("%s", string(b))
result = append(result, tmpString)
}

case "POST":
name := request.PostFormValue("name")
st, err := db.Prepare("INSERT INTO pandas(name) VALUES(?)")
if err != nil {
fmt.Print(err)
}
res, err := st.Exec(name)
if err != nil {
fmt.Print(err)
}

if res != nil {
result = append(result, "true")
}

case "PUT":
name := request.PostFormValue("name")
id := request.PostFormValue("id")

st, err := db.Prepare("UPDATE pandas SET name=? WHERE id=?")
if err != nil {
fmt.Print(err)
}
res, err := st.Exec(name, id)
if err != nil {
fmt.Print(err)
}

if res != nil {
result = append(result, "true")
}
case "DELETE":
id := strings.Replace(request.URL.Path, "/api/", "", -1)
st, err := db.Prepare("DELETE FROM pandas WHERE id=?")
if err != nil {
fmt.Print(err)
}
res, err := st.Exec(id)
if err != nil {
fmt.Print(err)
}

if res != nil {
result = append(result, "true")
}

default:
}

json, err := json.Marshal(result)
if err != nil {
fmt.Println(err)
return
}
//can't define dynamic slice in golang
var result = make([]string,1000)

switch request.Method {
case "GET":
st, err := db.Prepare("select * from pandas limit 10")
if err != nil{
fmt.Print( err );
}
rows, err := st.Query()
if err != nil {
fmt.Print( err )
}
i := 0
for rows.Next() {
var name string
var id int
err = rows.Scan( &id, &name )
panda := &Panda{Id: id,Name:name}
b, err := json.Marshal(panda)
if err != nil {
fmt.Println(err)
return
}
result[i] = fmt.Sprintf("%s", string(b))
i++
}
result = result[:i]

case "POST":
name := request.PostFormValue("name")
st, err := db.Prepare("INSERT INTO pandas(name) VALUES(?)")
if err != nil{
fmt.Print( err );
}
res, err := st.Exec(name)
if err != nil {
fmt.Print( err )
}

if res!=nil{
result[0] = "true"
}
result = result[:1]

case "PUT":
name := request.PostFormValue("name")
id := request.PostFormValue("id")

st, err := db.Prepare("UPDATE pandas SET name=? WHERE id=?")
if err != nil{
fmt.Print( err );
}
res, err := st.Exec(name,id)
if err != nil {
fmt.Print( err )
}

if res!=nil{
result[0] = "true"
}
result = result[:1]
case "DELETE":
id := strings.Replace(request.URL.Path,"/api/","",-1)
st, err := db.Prepare("DELETE FROM pandas WHERE id=?")
if err != nil{
fmt.Print( err );
}
res, err := st.Exec(id)
if err != nil {
fmt.Print( err )
}

if res!=nil{
result[0] = "true"
}
result = result[:1]

default:
}

json, err := json.Marshal(result)
if err != nil {
fmt.Println(err)
return
}

// Send the text diagnostics to the client.
fmt.Fprintf(response, "%v\n", string(json))
fmt.Fprintf(response,"%v",string(json))
//fmt.Fprintf(response, " request.URL.Path '%v'\n", request.Method)
db.Close()
db.Close()
}

func main() {

flag.Parse() // parse the command line args

// TODO: move connect string here

port := *apiport
var err string
func main(){
port := 1234
var err string
portstring := strconv.Itoa(port)

mux := http.NewServeMux()
mux.Handle("/api/", http.HandlerFunc(APIHandler))
mux.Handle("/", http.HandlerFunc(Handler))
mux.Handle("/api/", http.HandlerFunc( APIHandler ))
mux.Handle("/", http.HandlerFunc( Handler ))

// Start listing on a given port with these routes on this server.
log.Print("Listening on port " + portstring + " ... ")
errs := http.ListenAndServe(":"+portstring, mux)
errs := http.ListenAndServe(":" + portstring, mux)
if errs != nil {
log.Fatal("ListenAndServe error: ", err)
}
Expand Down

0 comments on commit f099bb4

Please sign in to comment.