dataserver test code

main.go

 

package main

import (
    "database/sql"
    "fmt"
    "log"
    "net/http"
    "time"

    _ "github.com/go-sql-driver/mysql"
)

func main() {
    http.HandleFunc("/getuser", getuser)
    s := &http.Server{
        Addr:           ":92",
        ReadTimeout:    30 * time.Second,
        WriteTimeout:   30 * time.Second,
        MaxHeaderBytes: 1 << 20,
    }
    log.Fatal(s.ListenAndServe())
}

func getuser(w http.ResponseWriter, r *http.Request) {

    w.Write([]byte(getuser_json()))
}

func getuser_json() string {
    db, err := sql.Open("mysql", "root:root@tcp(localhost:3306)/dataserver2?charset=utf8")
    if err != nil {
        panic(err.Error())
    }
    defer db.Close()
    zsql := fmt.Sprintf("insert into test(title) values('92:%v')", GetGuid())
    _, err = db.Query(zsql)
    if err != nil {
        panic(err.Error())
    }

    if err != nil {
        return err.Error()
    } else {
        return "ok"
    }

}

 

guid.go

 

package main

import (
    "crypto/md5"
    "crypto/rand"
    "encoding/base64"
    "encoding/hex"
    "io"
)

func GetMd5String(s string) string {
    h := md5.New()
    h.Write([]byte(s))
    return hex.EncodeToString(h.Sum(nil))
}

func GetGuid() string {
    b := make([]byte, 48)

    if _, err := io.ReadFull(rand.Reader, b); err != nil {
        return ""
    }
    return GetMd5String(base64.URLEncoding.EncodeToString(b))
}

 

posted @ 2016-09-05 23:53  Ender.Lu  阅读(181)  评论(0编辑  收藏  举报