golang作为server向android提供数据服务

中间交换的数据是json ,后台数据库服务器是sqlserver2012

android通过post或者get方式访问

如get方式http://192.168.255.13:7080/tblFileList?tblFileList2_Title_search1=t01

 package main

 import (
"time"
"log"
"net/http"
"os"
_ "code.google.com/p/odbc"
"database/sql"
"fmt"
"encoding/json"
) //http://192.168.255.13:7080/tblFileList?tblFileList2_Title_search1=t01 func get_tblFileList(w http.ResponseWriter, r *http.Request) { log.Print(r.RequestURI)
tblFileList2_Title_search1 := r.FormValue("tblFileList2_Title_search1")
tblFileList2_Title_search2 := r.FormValue("tblFileList2_Title_search2") fmt.Println("参数:",tblFileList2_Title_search1,tblFileList2_Title_search2)
list:= getData(tblFileList2_Title_search1,tblFileList2_Title_search2)
body, err := json.Marshal(list)
if err == nil{
w.Write(body)
}else{
w.Write([]byte("error"))
} } func login(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("token=123"))
}
func main() { http.HandleFunc("/tblFileList", get_tblFileList)
http.HandleFunc("/login", login) log.Println("Start serving on port 7080") err := http.ListenAndServe(":7080", nil)
if err != nil{
fmt.Println(err)
} os.Exit(0)
} func getData(filter1 string ,filter2 string) []tblFileList {
conn, err := sql.Open("odbc", "driver={SQL Server Native Client 11.0};server=test;database=db1;uid=sa;pwd=sa1234;")
if err != nil {
fmt.Println("Connecting Error")
return nil
}
defer conn.Close()
filter_where :="1=1 "
if filter1!=""{
filter_where += " and title like '" + filter1 + "%'"
}
if filter2!=""{
filter_where += " and title like '%" + filter2 + "%'"
} zsql :=`select
Title,
ReadCount,
LastReadUser,
isnull(LastReadTime,cast('1900-01-01' as datetime)) as LastReadTime
from tblFileList where ` + filter_where
log.Println(zsql)
stmt, err := conn.Prepare(zsql)
if err != nil {
fmt.Println("Query Error", err)
return nil
}
defer stmt.Close()
row, err := stmt.Query()
if err != nil {
fmt.Println("Query Error", err)
return nil
}
defer row.Close() rowlist :=[]tblFileList{}
for row.Next() {
var Title string
var ReadCount int
var LastReadUser string
var LastReadTime time.Time
if err := row.Scan(&Title, &ReadCount, &LastReadUser, &LastReadTime); err == nil {
//fmt.Println(Title, ReadCount,LastReadUser,LastReadTime)
var detail tblFileList detail.Title = Title
detail.ReadCount = ReadCount
detail.LastReadUser = LastReadUser
detail.LastReadTime = LastReadTime
if err != nil {
panic(err.Error())
}
rowlist = append(rowlist,detail,) } else {
fmt.Println("data Error", err)
}
} fmt.Printf("%s\n", "finish" ,len(rowlist))
return rowlist;
} type tblFileList struct {
Title string `json:"Title"`
ReadCount int `json:"ReadCount"`
LastReadUser string `json:"LastReadUser"`
LastReadTime time.Time `json:"LastReadTime"`
}
上一篇:Java开发从零开始填坑


下一篇:2014第8周一JS正则小问题