daily pastebin goal
57%
SHARE
TWEET

Untitled

a guest Jun 5th, 2018 57 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package main
  2.  
  3. import (
  4.     "database/sql"
  5.     _ "github.com/go-sql-driver/mysql"
  6.     "github.com/julienschmidt/httprouter"
  7.     "log"
  8.     "net/http"
  9.     "encoding/json"
  10.     "fmt"
  11.     "io/ioutil"
  12. )
  13.  
  14. var database *sql.DB
  15.  
  16. func getJSON(sqlString string) ([]byte, error) {
  17.     rows, err := database.Query(sqlString)
  18.     if err != nil {
  19.         return nil, err
  20.     }
  21.     defer rows.Close()
  22.     columns, err := rows.Columns()
  23.     if err != nil {
  24.         return nil, err
  25.     }
  26.     count := len(columns)
  27.     tableData := make([]map[string]interface{}, 0)
  28.     values := make([]interface{}, count)
  29.     valuePtrs := make([]interface{}, count)
  30.     for rows.Next() {
  31.         for i := 0; i < count; i++ {
  32.             valuePtrs[i] = &values[i]
  33.         }
  34.         rows.Scan(valuePtrs...)
  35.         entry := make(map[string]interface{})
  36.         for i, col := range columns {
  37.             var v interface{}
  38.             val := values[i]
  39.             b, ok := val.([]byte)
  40.             if ok {
  41.                 v = string(b)
  42.             } else {
  43.                 v = val
  44.             }
  45.             entry[col] = v
  46.         }
  47.         tableData = append(tableData, entry)
  48.     }
  49.     if len(tableData) == 0 {
  50.         return nil, nil
  51.     }
  52.     jsonData, err := json.Marshal(tableData)
  53.     if err != nil {
  54.         return nil, err
  55.     }
  56.  
  57.     return jsonData, nil
  58. }
  59.  
  60. func getUserStats(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  61.     err := database.Ping()
  62.     if err != nil {
  63.         log.Fatal(err)
  64.     }
  65.     response, err := getJSON("select * from stats where user_id = " + ps.ByName("user"))
  66.     if  response != nil{
  67.         w.Header().Set("Content-Type", "application/json")
  68.         w.Write(response)
  69.     } else {
  70.         http.Error(w, "User not found", 404)
  71.     }
  72. }
  73.  
  74. func handlePost(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  75.     user := ps.ByName("user")
  76.     response, err := getJSON("select * from stats where user_id = " + user)
  77.     if err != nil {
  78.         log.Fatal(err)
  79.     }
  80.     if response == nil {
  81.         stmt, err := database.Prepare("INSERT INTO stats(user_id, courses_completed, longest_streak, started_courses, " +
  82.             "last_logged_in, logged_in_since) VALUES(?, ?, ?, ?, ?, ?)")
  83.         if err != nil {
  84.             log.Fatal(err)
  85.         }
  86.         _, err = stmt.Exec(user, 0, 0, 0, nil, nil)
  87.         if err != nil {
  88.             log.Fatal(err)
  89.         }
  90.     }
  91.     resp, err := http.Get("http://localhost:8182/" + user)
  92.     if err != nil {
  93.         log.Fatal(err)
  94.     }
  95.     body, err := ioutil.ReadAll(resp.Body)
  96.     if err != nil {
  97.         fmt.Println(err)
  98.     }
  99.     w.Header().Set("Content-Type", "application/json")
  100.     w.Write(body)
  101. }
  102.  
  103. func main() {
  104.     //user:password@protocol(host_ip:host_port)/database
  105.     var err error
  106.     database, err = sql.Open("mysql", "stats-service:mysqlpassword@tcp(127.0.0.1:3306)/statsdb")
  107.     if err != nil{
  108.         log.Fatal(err)
  109.     }
  110.     defer database.Close()
  111.     router := httprouter.New()
  112.     router.GET("/:user", getUserStats)
  113.     router.POST("/:user/ping", handlePost)
  114.     err = http.ListenAndServe(":8181", router)
  115.     if err != nil {
  116.         log.Fatal(err)
  117.     }
  118. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top